<?php

/**
 * 新版本,每个咨询类型. 单独定价.
 */

namespace app\v4\controller;

use app\service\paipan;
use app\service\WxService;
use Jetfuel\SolarLunar\Solar;
use Jetfuel\SolarLunar\SolarLunar;
use think\cache\driver\Redis;
use think\Db;
use think\Exception;
use think\facade\Log;

class Index
{
    /**
     * 分类下包含的预测问题.
     *
     * @return void
     */
    private $audit = 0; //是否是审核中  1 是 0  否;

    public function calJinan()
    {
        $res = ['code' => 0, 'data' => [], 'msg' => ''];
        // 就是在特殊编号里的前提下 && 火3相生的3火7土8土=会，其他都是不会。
        $numSn = '633667(1)';
        $jinanMatch = $this->_getNumsnAttr($numSn);

        $res['data']['cate'] = '极难事件';
        $res['data']['res'] = '不会';
        if (in_array($numSn, config('app.special_group')) && $jinanMatch) {
            $res['data']['res'] = '会';
        }

        return json($res);
    }

    /**
     * 处理中医反馈.
     */
    public function dealMedicalFeedback()
    {
        $params = input('');
        $res = ['code' => 0, 'data' => [], 'msg' => ''];

        if (empty($params['feedType']) || !in_array($params['feedType'], [1, 2]) || empty($params['userPhone']) || empty($params['feedIds'])) {
            $res['code'] = 1;
            $res['msg'] = '参数不完整';

            return json($res);
        }
        // 更新诊断记录
        $memInfo = Db::name('member')->field('id,openid')->where(['phone' => $params['userPhone']])->find();

        if (empty($memInfo)) {
            $res['code'] = 1;
            $res['msg'] = '参数不完整';

            return json($res);
        }
        $medicalInfo = Db::name('new_user_question_history')->field('id,medical_is_effect')->where(['id' => $params['feedIds'], 'user_phone' => $params['userPhone']])->find();

        if (empty($medicalInfo) || $medicalInfo['medical_is_effect'] > 0) {
            $res['code'] = 1;
            $res['msg'] = '当前记录不允许此操作!';

            return json($res);
        }

        Db::startTrans();
        $updateRes1 = Db::name('new_user_question_history')->where(['id' => $params['feedIds'], 'user_phone' => $params['userPhone']])->update(['medical_is_effect' => $params['feedType']]);
        // 推送免费体检次数(只针对中医)
        // 只有 反馈正确,才增加medical_once_nums
        $updateRes2 = true;
        if ($params['feedType'] == 2) {
            $updateRes2 = Db::name('member')->where(['phone' => $params['userPhone']])->setInc('medical_once_nums', 1);
        }

        if (!$updateRes1 || !$updateRes2) {
            $res['code'] = 1;
            $res['msg'] = '诊断反馈提交失败!';
            Db::rollback();
        }
        if ($updateRes1 && $updateRes2) {
            Db::commit();
            // 推送会员模板消息
            $wxService = new WxService();
            $wxService->getAccessToken();
            $sendData = [
                'touser' => $memInfo['openid'],
                // 推送活动体验值到账提醒
                'template_id' => 'YgFksfqNSncg4AeYrmdZuCk0QSn2kJknREys4ha3tCk',
                'page' => 'pages/newDetail/indexV2?type=1-1-5&cid3=19',
                'data' => [
                    'thing1' => [
                        'value' => '中医诊断反馈,体验券回馈',
                    ],
                    'thing5' => [
                        'value' => '本体验券只能用于中医诊断及体检喔!',
                    ],
                    'number2' => [
                        'value' => 1,
                    ],
                    'time3' => [
                        'value' => '2024-12-14 09:11:00',
                    ],
                ],
            ];

            $sendRes = $wxService->messageSubscribeSend($sendData);
            Log::write('SendSubscribeTmpl::'.json_encode($sendRes, true));
        }

        return json($res);
    }

    /**
     ** 提问日期, 年月日的, 计算与那一天相匹配的五行属性.
     */
    private function _getSuitDateWuXing($year = '', $month = '', $date = '')
    {
        if (empty($year) || empty($month) || empty($date)) {
            return false;
        }

        $pai = new paipan();

        $info = $pai->GetGZ($year, $month, $date, 0);
        // 取出日期的地支 索引. 12地支的索引最大11, 给12 方便查错
        $earthIndex = isset($info[1][2]) ? $info[1][2] : 12;

        if ($earthIndex == 12) {
            return false;
        }
        // key: 按12地支,子/丑.., value: 与该地支的五行属性相匹配的 八卦编号. (1金,2金,3火,4木,5木,6水,7土,8土)
        // 根据上面的 $earthIndex, 得出对应的 小程序 中, 与地支相匹配的 代号
        $binWuXing = ['6x', '7x', '7a', '4x', '5x', '5a', '3x', '8x', '8a', '2x', '1x', '1a'];

        $noConflict = config('app.earth_to_wuxing');
        // echo $binWuXing[$earthIndex]; print_r($noConflict[$binWuXing[$earthIndex]]);exit;
        return $noConflict[$binWuXing[$earthIndex]];
    }

    /**
     * 通过生肖获取, 生肖对应的 体质判断.
     */
    private function _getInfoByAnimal($animalVal = '')
    {
        $animal = config('app.animal_order');
        $animalIndex = array_search($animalVal, $animal);
        $animalHotOrCold = config('app.animal_hot_or_cold');
        $annimalIll = config('app.animal_ill');

        return [
            'hot_or_cold' => $animalHotOrCold[$animalIndex],
            'animal_ill' => $annimalIll[$animalIndex],
        ];
    }

    /**
     * 根据出生年月日 返回 数据.
     */
    private function _birthday($mydate, $symbol = '-')
    {
        //计算年龄
        $birth = $mydate;
        list($by, $bm, $bd) = explode($symbol, $birth);
        // 先将 公历转换为农历
        $solar = Solar::create($by, $bm, $bd);
        $lunar = SolarLunar::solarToLunar($solar);
        // 将年转换为 阴历年
        $by = $lunar->year;
        $lunarDateStr = $lunar->year.'-'.$lunar->month.'-'.$lunar->day.' 00:00:00';
        $mydate = $lunarDateStr;
        // 月份不带 前0
        $cm = date('n', strtotime($mydate));
        // 日期 带0
        $cd = date('d', strtotime($mydate));
        // $age=date('Y')-$by-1;

        //计算生肖
        $animals = config('app.animal_order');
        $key = ($by - 1900) % 12;
        // 	echo $animals[$key];die();
        return [
            'animal' => $animals[$key],
            'lunar_year' => $lunar->year,
            'month' => $cm,
            'day' => $cd,
        ];
    }

    /**
     * 根据 月份和日期, 推测体质.
     */
    private function _getTizhiByMonthAndDay($month = 0, $day = 0)
    {
        if (empty($month) || empty($day)) {
            return '月份和日期格式不正确!';
        }

        $monAndDay = intval($month.$day);

        switch ($monAndDay) {
            case $monAndDay >= 101 && $monAndDay <= 120:
                return '11月23日 至 次年1月21日出生的人, 怕冷, 容易实现患关节炎、腰椎病.';
                break;
            case $monAndDay >= 121 && $monAndDay <= 321:
                return '每年1月21日 至 3月21日出生的人肝气旺.';
                break;
            case $monAndDay >= 322 && $monAndDay <= 521:
                return '3月22日 至 5月21日出生的人, 心火旺, 易患皮肤病.';
                break;
            case $monAndDay >= 522 && $monAndDay <= 722:
                return '5月22日 至 7月22日出生的人, 相火旺, 怕热, 易上火.';
                break;
            case $monAndDay >= 723 && $monAndDay <= 922:
                return '7月23日 至 9月22日出生的人, 脾胃较差, 胃寒, 易患关节炎.';
                break;
            case $monAndDay >= 923 && $monAndDay <= 1122:
                return '9月23日 至 11月22日出生的人, 大肠功能较差, 容易实现腹泻或便秘, 汗多, 患颈椎病.';
                break;
            case $monAndDay >= 1123 && $monAndDay <= 1231:
                return '11月23日 至 次年1月21日出生的人, 怕冷, 容易实现患关节炎、腰椎病.';
                break;
            default:
                return '未检测出异常';
                break;
        }
    }

    /**
     * 预测体制查询.
     *
     * @params $annimalInfo 出生年月日(阳历) >> 转换为 阴历后的生肖属性
     */
    private function _getChineseZodiac($year)
    {
        // 生肖数组，按顺序排列
        $zodiacs = ['鼠', '牛', '虎', '兔', '龙', '蛇', '马', '羊', '猴', '鸡', '狗', '猪'];

        // 计算生肖索引（2020 年是鼠年，作为一个基准）
        $index = ($year - 2020) % 12;
        if ($index < 0) {
            $index += 12;
        }

        // 返回对应的生肖
        return $zodiacs[$index];
    }

    private function getPredictTizhiSearch($annimalInfo = [])
    {
        // $annimalInfo['animal'] = '鼠';
        // 出生年(阴历年, 尾数)
        $birthYearEnd = substr($annimalInfo['lunar_year'], 3);
        $predictYears = [2025, 2026, 2027, 2028, 2029, 2030];
        $resp = [];
        $tizhiAndTiangan = config('app.tizhi_predict')['tizhi_and_tiangan'];
        $sixQi = config('app.tizhi_predict')['six_qi'];
        $fiveYun = config('app.tizhi_predict')['five_yun'];
        $sixTizhi = config('app.tizhi_predict')['six_tizhi'];
        $sixTizhiDiffMonth = config('app.tizhi_predict')['six_tizhi_diff_month'];

        // 六气客主加临的病理特点
        foreach ($predictYears as $k => $year) {
            // 获取预测年份的生肖
            $predictYearAnimal = $this->_getChineseZodiac($year);
            // $predictYearAnimal = '马';
            $yearEnd = substr($year, 3);
            // 体质与天干年份的叠加影响
            $resp[$k]['tizhi_and_tiangan'] = '';
            $resp[$k]['six_qi'] = '';
            $resp[$k]['five_yun'] = '';
            $resp[$k]['six_tizhi'] = '';
            // $resp[$k]['six_tizhi_diff_month'] = '';
            $resp[$k]['predict_year'] = $year;
            // 体质与天干年份的叠加影响
            foreach ($tizhiAndTiangan as $t => $item) {
                if ($yearEnd == $item[0] && in_array($annimalInfo['animal'], $item[1])) {
                    $resp[$k]['tizhi_and_tiangan'] = $item[2];
                }
            }
            // 六气客主加临的病理特点
            foreach ($sixQi as $n => $s) {
                if (in_array($annimalInfo['animal'], $s[0]) && in_array($predictYearAnimal, $s[0])) {
                    $resp[$k]['six_qi'] = $s[1];
                }
            }
            // 五运体质分类
            foreach ($fiveYun as $f => $yun) {
                if ($yun[0] == $birthYearEnd && $yearEnd == $yun[0]) {
                    $resp[$k]['five_yun'] = $yun[1];
                }
            }
            // 六气体质
            foreach ($sixTizhi as $six => $desc) {
                if (in_array($annimalInfo['animal'], $desc[0]) && in_array($predictYearAnimal, $desc[0])) {
                    $resp[$k]['six_tizhi'] = $desc[1];
                }
            }
            // 月份与六气主气的对应症状(通用规律)
            $resp[$k]['month'] = [];
            for ($mon = 1; $mon <= 12; ++$mon) {
                // 初之气（1-3月，厥阴风木）：风盛则肝郁体质（木运太过（生年尾数2））易现偏头痛，水运不及（年尾数1）者易受风寒感冒。
                if (in_array($mon, [1, 2, 3]) && $birthYearEnd == 2) {
                    $resp[$k]['month'][$mon] = '易现偏头痛';
                }
                if (in_array($mon, [1, 2, 3]) && $birthYearEnd == 1) {
                    $resp[$k]['month'][$mon] = '易受风寒感冒';
                }

                if (in_array($mon, [4, 5]) && $birthYearEnd == 3) {
                    $resp[$k]['month'][$mon] = '易心悸';
                }
                if (in_array($mon, [4, 5]) && $birthYearEnd == 4) {
                    $resp[$k]['month'][$mon] = '易口舌生疮';
                }
                // 三之气（6-7月，少阳相火）：暑热加重相火体质（火运太过（生年尾号8））痤疮，水运不及（生年尾数1）者易中暑。
                if (in_array($mon, [6, 7]) && $birthYearEnd == 8) {
                    $resp[$k]['month'][$mon] = '痤疮';
                }
                if (in_array($mon, [6, 7]) && $birthYearEnd == 1) {
                    $resp[$k]['month'][$mon] = '易中暑';
                }

                if (in_array($mon, [8, 9]) && $birthYearEnd == 9) {
                    $resp[$k]['month'][$mon] = '腹胀';
                }
                if (in_array($mon, [8, 9]) && $birthYearEnd == 0) {
                    $resp[$k]['month'][$mon] = '易痰多';
                }

                if (in_array($mon, [10, 11]) && $birthYearEnd == 0) {
                    $resp[$k]['month'][$mon] = '干咳';
                }

                if (in_array($mon, [11, 12, 1]) && $birthYearEnd == 1) {
                    $resp[$k]['month'][$mon] = '腰冷';
                }
                if (in_array($mon, [11, 12, 1]) && $birthYearEnd == 3) {
                    $resp[$k]['month'][$mon] = '四肢不温';
                }
            }
            // 六气体质在不同年月的症状(私有)
            $resp[$k]['private_month'] = [];
            for ($mon = 1; $mon <= 12; ++$mon) {
                foreach ($sixTizhiDiffMonth as $six => $diff) {
                    // 出生年 && 预测年, 在配置里面 + 预测年的尾数
                    if (in_array($annimalInfo['animal'], $diff[0]) && in_array($predictYearAnimal, $diff[0]) && $yearEnd == $diff[1] && in_array($mon, $diff[2])) {
                        $resp[$k]['private_month'][$mon] = $diff[3];
                    }
                }
            }
        }

        return ['predictYears' => $predictYears, 'predictRes' => $resp];
    }

    /**
     * 获取体质查询结果.
     */
    public function getTizhiSearch()
    {
        $res = ['code' => 0, 'data' => [], 'msg' => ''];
        $birthTimeArr = config('app.birth_time');
        $birthTimeIndex = input('birthTime', -1);
        $birthDate = input('date', '');
        $birthPlace = input('birthPlace', '');
        // Log::info('生日::'.$birthDate);
        if ($birthTimeIndex < 0 || empty($birthDate) || empty($birthPlace)) {
            $res['code'] = 1;
            $res['msg'] = '出生日期,时间,出生省份不能为空!';

            return json($res);
        }
        // 匹配到出生省份区域
        $areaInfo = config('app.area_info');
        $birthPlaceDescription = '';
        foreach ($areaInfo as $section => $rowData) {
            if (in_array($birthPlace, $rowData['areas'])) {
                $birthPlaceDescription = $rowData['description'];
                break;
            }
        }
        // 截取 年的最后一个数字
        $yearStand = config('app.year_end_stand');
        $yearEnd = substr(substr($birthDate, 0, 4), 3, 1);
        // 除开年,按照阴历, 月份和日期, 按照阳历的日期
        $monthEnd = substr($birthDate, 5, 2);
        $dayEnd = substr($birthDate, 8, 2);
        // 获取年份对应的 生肖&&月份&&日期
        $animalInfo = $this->_birthday($birthDate);
        // 如果选择了预测
        $predictRes = [];
        if (input('isPredict') == 'true') {
            $predictRes = $this->getPredictTizhiSearch($animalInfo);
        }

        $predictInfo = $this->_getInfoByAnimal($animalInfo['animal']);
        // 除开年,按照阴历, 月份和日期, 按照阳历的日期(PS: 2025-03-18需求)
        // $monthAndDayInfo = $this->_getTizhiByMonthAndDay($animalInfo['month'], $animalInfo['day']);
        $monthAndDayInfo = $this->_getTizhiByMonthAndDay($monthEnd, $dayEnd);

        // 通过 $birthTimeIndex 匹配 体质
        $birthTimeStand = config('app.birth_time_stand');

        try {
            // .'--'.$predictInfo['animal_ill']
            $tempStr = $predictInfo['hot_or_cold'];

            $res['data'] = [
                // 出生年尾数, 代替寓意
                'year_end' => $yearStand[$yearEnd],
                // 属相 代替寓意
                'zodiac' => $tempStr,
                // 'zodiac' => $predictInfo['hot_or_cold'],
                'animal_ill' => $predictInfo['animal_ill'],
                // 月份和日期 代替寓意
                'month_day' => $monthAndDayInfo,
                // 具体时间点 代替寓意
                'detail_time' => $birthTimeStand[$birthTimeIndex],
                'birth_place_description' => $birthPlaceDescription,
                // 预测信息
                'predict_res' => $predictRes,
            ];
            // 是否是, 体制查询日卡来源
            $isTizhiDayFree = input('usedDay', 0);
            // 有体验标识, 设置它的体验日期
            if ($isTizhiDayFree == 200) {
                $redis = new Redis();
                $ip = $_SERVER['REMOTE_ADDR'];
                $cacheKeyUsed = $ip.'_used_day';
                $cacheUsedKeyExists = $redis->handler()->set($cacheKeyUsed, date('Y-m-d', time()));
            }

            return json($res);
        } catch (\Throwable $th) {
            $res['code'] = 1;
            $res['msg'] = $th->getMessage();

            return json($res);
        }
    }

    /**
     * 根据当前选择的 一级类型编号: 1-团体用户 ,2-个人用户.
     * 二级类型编号. 个人用户下: 7-项目预测,8-工作事业...
     */
    public function getQuestionList()
    {
        $res = ['code' => 1, 'data' => [], 'msg' => ''];
        try {
            $cid3 = input('cid3', 0);
            $con[] = ['cid3', '=', $cid3];
            $con[] = ['status', '>', 0];

            $data = Db::name('question')->field('*')->where($con)->select();
            foreach ($data  as $key => $value) {
                $value['prompts'] = explode(',', $value['prompts']);
                $value['questions'] = explode(',', $value['questions']);
                $res['data'][] = $value;
            }
            $res['code'] = 0;

            return json($res);
        } catch (\Throwable $th) {
            $res['code'] = 1;
            $res['msg'] = $th->getMessage();

            return json($res);
        }
    }

    /**
     * 最新版本AI预测.
     */
    public function latestPersonPredict()
    {
        $res = ['code' => 1, 'data' => [], 'msg' => ''];
        try {
            $user_phone = input('user_phone', '');
            //是否是健康预测  1 是 0 否 目前就 58 59两个问题
            $is_health = input('is_health', 0);
            if (empty($user_phone)) {
                throw new Exception('手机号为必填参数', 1);
            }
            //记录时间是否应该付费  0 付费 1免费(默认支付)
            // $time_pay = input('time_pay', 0);
            $question_id = input('question_id', 0);
            $data = Db::name('question')->field('*')->where(['id' => $question_id])->find();

            if (empty($data)) {
                throw new Exception('Error question_id', 1);
            }

            $type = $data['answer_type'];
            // 查询当前用户, 在当前类型下,是否有可用套餐
            // 用户无可用套餐, 不允许咨询
            $memField = 'id,once_nums,month_day,works_once_nums,works_month_nums,emotion_once_nums,emotion_month_nums,pr_once_nums,pr_month_nums,group_once_nums,group_month_nums,stu_once_nums,stu_month_nums,medical_once_nums';
            $userComboInfo = Db::name('member')->field($memField)->where(['phone' => $user_phone])->find();

            if (empty($userComboInfo)) {
                throw new Exception('没有套餐,不允许咨询', 1);
            }
            // 根据每个咨询. 目前有看广告咨询. 前端在显示按钮的时候,做了判断. 是否有免费按钮
            // switch ($type) {
            //     case 1:
            //         if ($userComboInfo['once_nums'] <= 0 && $userComboInfo['month_day'] <= 0) {
            //             throw new Exception("项目咨询-无可用咨询套餐", 1);
            //         }
            //         break;
            //     case 2:
            //         if ($userComboInfo['works_once_nums'] <= 0 && $userComboInfo['works_month_nums'] <= 0) {
            //             throw new Exception("工作事业-无可用咨询套餐", 1);
            //         }
            //         break;
            //     case 3:
            //         if ($userComboInfo['emotion_once_nums'] <= 0 && $userComboInfo['emotion_month_nums'] <= 0) {
            //             throw new Exception("情感咨询-无可用咨询套餐", 1);
            //         }
            //         break;
            //     case 4:
            //         if ($userComboInfo['pr_once_nums'] <= 0 && $userComboInfo['pr_month_nums'] <= 0) {
            //             throw new Exception("公关审核-无可用咨询套餐", 1);
            //         }
            //          break;
            //     case 5:
            //         if ($userComboInfo['group_once_nums'] <= 0 && $userComboInfo['group_month_nums'] <= 0) {
            //             throw new Exception("团体用户-无可用咨询套餐", 1);
            //         }
            //         break;
            //     case 6:
            //         if ($userComboInfo['stu_once_nums'] <= 0 && $userComboInfo['stu_month_nums'] <= 0) {
            //             throw new Exception("学业考研-无可用咨询套餐", 1);
            //         }
            //         break;
            //     case 7:
            //         if ($userComboInfo['medical_once_nums'] <= 0 && $userComboInfo['medical_once_nums'] <= 0) {
            //             throw new Exception("中医诊断健康-无可用咨询套餐", 1);
            //         }
            //         break;
            // }
            $input_data = [];
            $me_name = ''; //我方名称
            $ta_name = ''; //他方名称
            $params = [$data['tpl']];
            $questions = explode(',', $data['questions']);

            foreach ($questions as $question) {
                $val = input($question, '');
                $params[] = $val;
                if ($data['me_name_key'] == $question) {
                    $me_name = $val;
                }
                if ($data['ta_name_key'] == $question) {
                    $ta_name = $val;
                }
                $input_data[] = [$question, $val];
            }
            $question_msg = call_user_func_array('sprintf', $params);

            //预测日期
            $result_day = date('Y-m-d');
            $date1 = input('date1', '');
            $isShowTimes = $date1 == '' ? 0 : 1;
            //contact 固定 不用用户选择
            $contact = 1;
            //股市问题

            if (in_array($question_id, config('app.contact2'))) {
                $contact = 2;
            }
            //问题中 有 不可能事件 默认否
            if (in_array($question_id, config('app.contact0'))) {//股市问题
                $contact = 0;
            }
            // [58,59,75]
            if (in_array($question_id, config('medical_ids'))) {
                //健康预测
                $typeIds = Db::name('health')->field('id')->select();
            // $time_pay = 1;
            } elseif ($type == 2 || $type == 6) {
                // 随机取一个. 如果是: 工作事业选择: 2
                $typeIds = Db::name('docs_works')->field('id')->select();
            } else {
                // 随机取一个. 如果是: 项目预测:1 + 公关审核(含股票):4 + 公司用户:5
                if ($type == 1 || $type == 4 || $type == 5) {
                    $typeIds = Db::name('docs_latest')->field('id')->select();
                }

                // 随机取一个. 如果是: 情感咨询选择: 3
                if ($type == 3) {
                    $typeIds = Db::name('docs_emotion')->field('id')->select();
                }
            }

            $typeIdsArr = array_column($typeIds, 'id');
            // 从数组里面随机取出一个
            $key = array_rand($typeIdsArr, 2);
            if (empty($key)) {
                throw new Exception('预测失败', 1);
            }
            $result_id = $typeIdsArr[$key[0]];
            $ta_result_id = $typeIdsArr[$key[1]];

            //股市区间4个 时间会否收费
            //  $time_pay = 1;
            // if(in_array($question_id,[34,35,55,56]))   $time_pay = 0;
            $insertData = [
                'user_phone' => $user_phone,
                'person_menu_id' => $data['cid3'],
                'person_menu_item_id' => $data['id'],
                'person_fix_msg' => $question_msg,
                'result_id' => $result_id,
                'is_show_time_res' => $isShowTimes, //有预测日期
                'add_time' => date('Y-m-d H:i:s', time()),
                'result_type' => $data['answer_type'],
                'question_id' => $question_id,
                'ta_result_id' => $ta_result_id,
                'contact' => $contact,
                'date1' => $date1,
                'result_day' => $result_day,
                'rate' => 0,
                'me_name' => $me_name,
                'ta_name' => $ta_name,
                'input_data' => json_encode($input_data, JSON_UNESCAPED_UNICODE),
                // 'time_pay' => 1,
            ];
            $historyId = Db::name('new_user_question_history')->insertGetId($insertData);
            if ($historyId < 1) {
                throw new Exception('咨询失败', 1);
            }
            // 无月卡套餐, 扣减次数.有月卡继续执行
            switch ($type) {
                case 1:
                    if ($userComboInfo['month_day'] > 0) {
                        // 用户表扣减次数
                        Db::name('member')->where(['phone' => $user_phone])->setDec('once_nums');
                    }
                    break;
                case 2:
                    if ($userComboInfo['works_once_nums'] > 0) {
                        // 用户表扣减次数
                        Db::name('member')->where(['phone' => $user_phone])->setDec('works_once_nums');
                    }
                    break;
                case 3:
                    if ($userComboInfo['emotion_once_nums'] > 0) {
                        // 用户表扣减次数
                        Db::name('member')->where(['phone' => $user_phone])->setDec('emotion_once_nums');
                    }
                    break;
                case 4:
                    if ($userComboInfo['pr_once_nums'] > 0) {
                        // 用户表扣减次数
                        Db::name('member')->where(['phone' => $user_phone])->setDec('pr_once_nums');
                    }
                    break;
                case 5:
                    if ($userComboInfo['group_once_nums'] > 0) {
                        // 用户表扣减次数
                        Db::name('member')->where(['phone' => $user_phone])->setDec('group_once_nums');
                    }
                    break;
                case 6:
                    if ($userComboInfo['stu_once_nums'] > 0) {
                        // 用户表扣减次数
                        Db::name('member')->where(['phone' => $user_phone])->setDec('stu_once_nums');
                    }
                    break;
            }

            //股票专用 ===如果是团体/个人 公关审核第三个问题将提问id 放入缓存队列自动提问
            if (in_array($question_id, [34, 35, 55, 56])) {
                $redis = new Redis();
                $redis->handler()->lpush('autoList', $historyId);
            }
            $res['code'] = 0;
            $res['data']['history_id'] = $historyId;

            return json($res);
        } catch (\Throwable $th) {
            $res['code'] = 1;
            $res['msg'] = $th->getMessage();

            return json($res);
        }
    }

    //看广告免费咨询或查看
    public function adShow()
    {
        $res = ['code' => 1, 'data' => [], 'msg' => ''];
        $type = input('type', '1'); //看广告类型 1 付费咨询 2 查看日期 3 解决方案
        $user_phone = input('user_phone', '');
        $historyId = input('history_id', '0');
        try {
            if (empty($user_phone)) {
                throw new Exception('手机号为必填参数', 1);
            }
            //看广告免费咨询
            if ($type == 1) {
                $answer_type = input('answer_type', '');
                switch ($answer_type) {
                    case 1:
                        $result = Db::name('member')->where(['phone' => $user_phone])->update(['once_nums' => 1]);
                        break;
                    case 2:
                        $result = Db::name('member')->where(['phone' => $user_phone])->update(['works_once_nums' => 1]);
                        break;
                    case 3:
                        $result = Db::name('member')->where(['phone' => $user_phone])->update(['emotion_once_nums' => 1]);
                        break;
                    case 4:
                         $result = Db::name('member')->where(['phone' => $user_phone])->update(['pr_once_nums' => 1]);
                         break;
                    case 5:
                         $result = Db::name('member')->where(['phone' => $user_phone])->update(['group_once_nums' => 1]);
                        break;
                    case 6:
                         $result = Db::name('member')->where(['phone' => $user_phone])->update(['stu_once_nums' => 1]);
                        break;
                }
            }
            //日期免费查看
            // if($type == 2){
            //     if (empty($historyId)) {
            //         throw new Exception("咨询记录ID不能为空!", 1);
            //     }
            //     $result = Db::name('new_user_question_history')->where(['id' => $historyId])->update(['time_pay'=>1]);
            // }
            //解决方案
            if ($type == 3) {
                if (empty($historyId)) {
                    throw new Exception('咨询记录ID不能为空!', 1);
                }
                $result = Db::name('new_user_question_history')->where(['id' => $historyId])->update(['resolve_pay' => 1]);
            }

            $res['code'] = 0;

            return json($res);
        } catch (\Throwable $th) {
            $res['code'] = 1;
            $res['msg'] = $th->getMessage();

            return json($res);
        }
    }

    /**
     * 根据提问的年,推算出与年 五行相生的 编号.
     */
    private function _calSuitNumsnArr($yearOrMon = '', $type = 1)
    {
        // 匹配年的五行属性
        $match = [
            [[1984, 1996, 2008, 2020, 2032, 2044], '6x'],
            [[1985, 1997, 2009, 2021, 2033, 2045], '7x'],
            // 实际是7a
            [[1986, 1998, 2010, 2022, 2034, 2046], '7a'],
            [[1987, 1999, 2011, 2023, 2035, 2047], '4x'],
            [[1988, 2000, 2012, 2024, 2036, 2048], '5x'],
            // 5a
            [[1989, 2001, 2013, 2025, 2037, 2049], '5a'],
            [[1990, 2002, 2014, 2026, 2038, 2050], '3x'],
            [[1991, 2003, 2015, 2027, 2039, 2051], '8x'],
            // 8a
            [[1992, 2004, 2016, 2028, 2040, 2052], '8a'],
            [[1993, 2005, 2017, 2029, 2041, 2053], '2x'],
            [[1994, 2006, 2018, 2030, 2042, 2054], '1x'],
            // 1a
            [[1995, 2007, 2019, 2031, 2043, 2055], '1a'],
        ];
        // 我们 随机出来的编号对应的五行, 1金,2金,3火,4木,5木,6水,7土,8土
        // 年的五行属性 作为Key, key生的属性作为value.
        // 比如: 金生水, 顺向取. 不能逆向, 土生金就不行
        // 2020年=6 子/水,2021年=7 丑/土,2022年=7a 土,2023年=4 木,2024年=5 木,2025年=5a 木,2026年=3 火,2027年=8 土,2028年=8a 土,2029年=2 金,2030年=1 金,2031年=1a 金
        $noConflict = config('app.earth_to_wuxing');
        // 月份排列五行
        // 12月=6x，1月=7x，2月=7a，3月=4x，4月=5x，5月=5a，6月=3x，7月=8x，8月=8a，9月=2x，10月=1x，11月=1a
        if ($type == 2) {
            $match = [
                [[12], '6x'],
                [[1, '01'], '7x'],
                // 实际是7a
                [[2, '02'], '7a'],
                [[3, '03'], '4x'],
                [[4, '04'], '5x'],
                // 5a
                [[5, '05'], '5a'],
                [[6, '06'], '3x'],
                [[7, '07'], '8x'],
                // 8a
                [[8, '08'], '8a'],
                [[9, '09'], '2x'],
                [[10], '1x'],
                // 1a
                [[11], '1a'],
            ];
        }
        $yearKey = '';

        foreach ($match as $key => $yearsArr) {
            if (in_array($yearOrMon, $yearsArr[0])) {
                $yearKey = $yearsArr[1];
                break;
            }
        }

        // 当前yearKey, 相生的 编号数组
        $suitNumSnArr = $noConflict[$yearKey];

        return $suitNumSnArr;
    }

    /**
     ** 具体日期的,地支五行属性比较复杂点.
     */
    private function _getEarthlyBranch($date)
    {
        // 地支数组
        $earthlyBranches = [
            // key: 12地支, value: 匹配出来的编号,代表属性的编号
            '6a' => [4, 5, 6],
            '8a' => [1, 2, 7, 8],
            '5a' => [3, 4, 5],
            '5x' => [3, 4, 5],
            '8x' => [1, 2, 7, 8],
            '3a' => [3, 7, 8],
            '3x' => [3, 7, 8],
            '8y' => [1, 2, 7, 8],
            '1x' => [1, 2, 6],
            '1a' => [1, 2, 6],
            '8z' => [1, 2, 7, 8],
            '6x' => [4, 5, 6],
        ];
        $flag = ['1' => '金', '5' => '木', '6' => '水', '3' => '火', '8' => '土'];
        // 将日期转换为时间戳
        $timestamp = strtotime($date);

        // 获取年份
        $year = date('Y', $timestamp);

        // 计算地支的索引
        $index = ($year - 4) % 12; // 4年是甲子年
        $branches = array_keys($earthlyBranches);

        // 获取对应的地支
        $earthlyBranch = $branches[$index];
        $element = $earthlyBranches[$earthlyBranch];

        return $element;
    }

    /**
     * 获取编号中,括号里的数字
     * 编号的五行属性的算法.
     * 按()里的数字识别. 123的时候取第二位, 456的时候取第一位.
     */
    private function _getNumsnNumber($numSn = '')
    {
        if (empty($numSn)) {
            return 0;
        }

        preg_match_all('/\((\d+)\)/', $numSn, $matches);

        $attrSn = !empty($matches[1][0]) ? $matches[1][0] : 0;
        $index = in_array($attrSn, [1, 2, 3]) ? 1 : 0;

        return $numSn[$index];
    }

    /**
     * 根据编号 推出,属性是否符合. 极难事件.
     */
    private function _getNumsnAttr($numSn = '')
    {
        if (empty($numSn)) {
            return 0;
        }

        preg_match_all('/\((\d+)\)/', $numSn, $matches);
        $attrSn = !empty($matches[1][0]) ? $matches[1][0] : 0;
        // 括号里面, 是 1,2,3 则取编号 索引==1的数字, 4,5,6 则取 编号索引==0的数字
        $index = in_array($attrSn, [1, 2, 3]) ? 1 : 0;
        // 1金,2金,3火,4木,5木,6水,7土,8土
        // 目标2024~2043年,属火.
        // 与火相生的
        return in_array($numSn[$index], [3, 7, 8]) ? 1 : 0;
    }

    /**
     * 获取较难事件对应的结果:  容易实现|不易实现.
     */
    private function _getDiffNumsnAttr($numSn = '', $year = '')
    {
        if (empty($year)) {
            $year = date('Y', time());
        }
        if (empty($numSn)) {
            return 0;
        }

        preg_match_all('/\((\d+)\)/', $numSn, $matches);
        $attrSn = !empty($matches[1][0]) ? $matches[1][0] : 0;
        // 括号里面, 是 1,2,3 则取编号 索引==0的数字 与 编号第6位进行属性匹配, 4,5,6 则取 编号索引==1的数字 与编号第5位,进行属性匹配
        $index = in_array($attrSn, [1, 2, 3]) ? 0 : 1;
        // 1金,2金,3火,4木,5木,6水,7土,8土
        // 目标2024~2043年,属火.
        // 与火相生的
        // 默认使用当年,来得出 与当年 五行相生的 数字编号
        $liveArr = $this->_calSuitNumsnArr($year);
        // 测试编号: 171527(6)0
        // 最终的预测: 会(1)|不会(2), 容易实现(1)|不易实现(2)
        $finalTxt = 0;
        $wuxingArr = config('app.earth_to_wuxing');

        if ($index == 0) {
            $finalTxt = $this->_getFinalTxt(0, $numSn, $wuxingArr, $liveArr);
        }
        if ($index == 1) {
            $finalTxt = $this->_getFinalTxt(1, $numSn, $wuxingArr, $liveArr);
        }

        return $finalTxt;
    }

    private function _getFinalTxt($index, $numSn, $wuxingArr, $liveArr)
    {
        // 定义相应的位数
        $position1 = $numSn[$index];
        // 需要 被匹配的数字
        $position2 = $numSn[$index == 0 ? 5 : 4];
        // dump($index);dump($position1);dump($position2);dump($numSn);dump($position1 . 'x');dump($wuxingArr[$position1 . 'x']);die();
        // 第一步: 检查相生关系. 相生，直接返回 不会
        if (in_array($position2, $wuxingArr[$position1.'x'])) {
            return 2;
        }
        // 相克，进行第二步检查
        $finalTxt = 2;
        // 与年生. == 会
        if (in_array($position2, $liveArr)) {
            $finalTxt = 1;
        }
        // dump($index);dump($position2);dump($numSn);dump($liveArr);die();
        return $finalTxt;
    }

    /**
     * 替换需要标注展示的关键字.
     */
    private function _replaceTwoWords($inputString, $word1, $word2)
    {
        // 正则表达式匹配两个字
        $pattern = "/($word1)(.*?)(($word2))/u";
        // 替换成加粗的 <text> 标签
        $replacement = '<span style="color:red;font-weight:bold;">$1$3</span>';
        // 执行替换
        $result = preg_replace($pattern, $replacement, $inputString);

        return $result;
    }

    /**
     * 获取用户中医相关诊断的提问, 小程序端,新增中医诊断反馈.
     */
    public function getUserMedicalQuestion()
    {
        $res = ['code' => 0, 'data' => [], 'msg' => ''];
        try {
            $phone = input('user_phone', '');
            $pageRows = input('limit', 5);

            if (empty($phone)) {
                throw new Exception('未查询到咨询结果!', 1);
            }
            // 查询当前用户.中医诊断下的提问.
            $lists = Db::name('new_user_question_history')->field('id,person_fix_msg,result_day,medical_is_effect,add_time')->where(['user_phone' => $phone])->where('question_id', 'in', config('app.medical_ids'))->order('id', 'desc')->paginate($pageRows);
            if (!empty($lists->items())) {
                foreach ($lists->items() as $k => &$row) {
                    $row['num_sn'] = date('YmdHis', strtotime($row['add_time'])).$row['id'];
                    $lists[$k] = $row;
                }
            }
            $res['data'] = $lists;

            exit(json_encode($res, JSON_UNESCAPED_UNICODE));
        } catch (\Throwable $th) {
            $res['code'] = 1;
            $res['msg'] = $th->getMessage();

            return json($res);
        }
    }

    /**
     * 获取预测信息.
     *
     * @return void
     */
    public function getPredict()
    {
        $res = ['code' => 1, 'data' => [], 'msg' => ''];
        try {
            // 个人 咨询,历史记录   145620
            $historyId = input('history_id', '0');
            //是否隐藏其他选项 默认 1 显示  2 隐藏
            $isHidden = input('isHidden', '2');
            //是否是ios  1 是 0 否
            $isIos = input('isIos', 0);

            if ($historyId == 153308) {
                $historyId = 153577;
            }

            $flag = input('flag', 0); //是否记录缓存的标志
            if (empty($historyId)) {
                throw new Exception('咨询记录ID不能为空!', 1);
            }
            // 根据 $historyId, 得出它咨询所 得到的答案ID
            $historyInfo = Db::name('new_user_question_history')->field('*')->where(['id' => $historyId])->find();

            $phone = $historyInfo['user_phone'];
            // print_r($historyInfo);exit;
            if (empty($historyInfo)) {
                throw new Exception('未查询到咨询结果!', 1);
            }

            //v4 新数据逻辑
            $meResultId = $historyInfo['result_id'];
            $taResultId = $historyInfo['ta_result_id'];
            // 用户提问信息
            $personTpl = $historyInfo['person_fix_msg'];

            $type = $historyInfo['person_menu_id'];
            $table = 'docs_latest'; ////项目预测
            if ($type == '2' || $type == '8' || $type == '20') {
                $table = 'docs_works'; //工作事业
            }
            if ($type == '3' || $type == '9') {
                $table = 'docs_emotion'; //工作事业
            }
            if ($type == '19') {
                $table = 'health'; //健康预测
            }

            $infoMe = Db::name($table)->field('*')->where(['id' => $meResultId])->find();

            $infoTa = Db::name($table)->field('*')->where(['id' => $taResultId])->find();

            if (empty($infoMe) || empty($infoTa)) {
                throw new Exception('未查询到咨询结果!', 1);
            }

            $num_sn = $infoMe['num_sn'];

            $me = $num_sn[7] > 3 ? $num_sn[1] : $num_sn[0];
            $ta = $num_sn[7] > 3 ? $num_sn[0] : $num_sn[1];
            // print_r($num_sn);exit;
            //使用me的编号进行预测
            if (!empty($historyInfo['me_name']) && empty($historyInfo['ta_name'])) {
                $tmp = $ta;
                $ta = $me;
                $me = $tmp;
            }

            $startdate = $enddate = $startenddate1 = '';
            $startenddate = [];
            $input_data_arr = json_decode($historyInfo['input_data'], true);

            if (is_array($input_data_arr)) {
                foreach ($input_data_arr as $value) {
                    if ($value[0] == 'startdate') {
                        $startdate = $value[1];
                    }
                    if ($value[0] == 'enddate') {
                        $enddate = $value[1];
                    }
                }
            }
            //非区间
            if ($startdate == '') {
                $date1 = $historyInfo['date1'];
                $fInfo = $this->_forecastDay($date1, $historyInfo, $ta, $num_sn);
                // dump($fInfo);exit;
                $easy = $fInfo['easy'];
            } else {
                //时间区间
                // if(in_array($historyInfo['question_id'],[34,35])){
                //     $dyss = $this->_date($historyInfo['input_data']);
                // }
                if (in_array($historyInfo['question_id'], [55, 56])) {
                    //因为55 56 存在多个日期 所以从新组装数组
                    $dyss = Db::name('new_user_question_history')->field('id,date1')->where(['pid' => $historyId])->select();
                    $range = [];
                    foreach ($dyss as $dy) {
                        $range[$dy['id']] = $dy['date1'];
                    }
                    $dyss = $range;
                } else {
                    $dyss = $this->_date($historyInfo['input_data']);
                }
                // var_dump($dyss);exit;
                if (is_array($dyss)) {
                    foreach ($dyss as $k => $day1) {
                        //挨个循环获取ta的值
                        if (in_array($historyInfo['question_id'], [34, 35])) {
                            $dayWhere['date1'] = $day1;
                            $dayWhere['pid'] = $historyId;
                        } elseif (in_array($historyInfo['question_id'], [55, 56])) {
                            $dayWhere['id'] = $k;
                        } else {
                            $dayWhere['id'] = $historyId;
                        }

                        $dayInfo = Db::name('new_user_question_history')->field('*')->where($dayWhere)->find();
                        $meResultId1 = $dayInfo['result_id'];
                        $taResultId1 = $dayInfo['ta_result_id'];
                        // 用户提问信息
                        $personTpl = $dayInfo['person_fix_msg'];

                        $type = $dayInfo['person_menu_id'];
                        $table = 'docs_latest'; ////项目预测
                        if ($type == '2' || $type == '8' || $type == '20') {
                            $table = 'docs_works'; //工作事业
                        }
                        if ($type == '3' || $type == '9') {
                            $table = 'docs_emotion'; //工作事业
                        }
                        $infoMe1 = Db::name($table)->field('*')->where(['id' => $meResultId1])->find();
                        $ta = $this->_getTa($dayInfo);

                        $fInfo = $this->_forecastDay($day1, $dayInfo, $ta, $infoMe1['num_sn']);

                        if ($fInfo['easy'] == 1) {
                            if ($dayInfo['contact'] == 2) {
                                $last_num1 = substr($infoMe1['num_sn'], -1);

                                if ($last_num1 == 1) {
                                    if (in_array($historyInfo['question_id'], [34, 35, 55, 56])) {
                                        $startenddate[] = $day1.'  '.$infoTa['ke_zhu_idea']; //如果是股市 尾号为1才显示会
                                    } else {
                                        $startenddate[] = $day1;
                                    }
                                }
                            } else {
                                if (!in_array($day1, $startenddate)) {
                                    if (in_array($historyInfo['question_id'], [34, 35])) {
                                        $startenddate[] = $day1; //如果是股市 尾号为1才显示会
                                    } elseif (in_array($historyInfo['question_id'], [55, 56])) {
                                        if ($dayInfo['ta_name1']) {
                                            //   $startenddate[] = $day1.' 会 '.$dayInfo['ta_name1'];
                                            $startenddate[] = $day1;
                                        } else {
                                            $startenddate[] = $day1;
                                        }
                                    } else {
                                        $startenddate[] = $day1;
                                    }
                                }
                            }
                        }
                    }

                    if ($startenddate) {
                        $startenddate1 = implode("\n", $startenddate);
                    } else {
                        $startenddate1 = '无';
                    }
                }

                $easy = $fInfo['easy'];
            }

            //手机号中间4位用****替代
            $historyInfo['user_phone'] = substr_replace($historyInfo['user_phone'], '****', 3, 4);
            //我方 另一方名称处理
            if (!empty($historyInfo['me_name']) && empty($historyInfo['ta_name'])) {
                $historyInfo['ta_name'] = $historyInfo['user_phone'];
            } elseif (empty($historyInfo['me_name'])) {
                $historyInfo['me_name'] = $historyInfo['user_phone'];
            }
            if ($table == 'docs_latest') {
                $resp = [
                    'num_sn' => $infoMe['num_sn'],
                    'question_msg' => $historyInfo['person_fix_msg'],
                    'is_get_profit' => $infoMe['is_get_profit'], //我方做该事件是否可以获得利益
                    'me_wants' => $infoMe['zixun_wants'], //我方推进意愿 zixun_wants
                    'ta_idea' => $infoTa['ke_zhu_idea'], //另一方对我的想法 ta ke_zhu_idea
                    'ta_xinli' => $infoMe['ke_zhu_idea'], //另一方对于该事件此时的心理活动 ta zixun_xinli
                    'ta_wants' => $infoTa['zixun_wants'], //对方增加事件内容一 ta zixun_wants
                    //年：月：日：
                    'year_good' => implode('、', $fInfo['yearGood']),
                    'month_good' => implode('、', $fInfo['monthGood']),
                    'day_good' => implode('、', $fInfo['dayGood']),
                    'easy' => $fInfo['easy'],
                    'date1' => $historyInfo['date1'], //咨询日期
                    'startenddate' => $startenddate1, //时间区间预测
                    'me_wants_date' => '我方有推进意愿的时间（年月日）'.$historyInfo['result_day'],
                    //对方增加事件内容二  我方有推进意愿的时间（年月日）
                    'ta_xintai' => $infoTa['zixun_xintai'], //客方心态 ta zixun_xintai
                    'me_xintai' => $infoMe['zixun_xintai'], //我方的心态 zixun_xintai
                    'things_degree' => $infoMe['things_degree'], //该事件总体推进难易度 things_degree
                    'me_xinli' => $infoMe['zixun_xinli'], //我方对于该事件此时的心理活动 zixun_xinli
                    'rate' => $historyInfo['rate'], //指定风险管理推送频率
                    'solution' => $infoMe['solution'], //解决方案
                    'is_show_time_res' => $historyInfo['is_show_time_res'],
                    'me_name' => empty($historyInfo['me_name']) ? '我方' : $historyInfo['me_name'],
                    'ta_name' => empty($historyInfo['ta_name']) ? '另一方' : $historyInfo['ta_name'],
                    'contact' => $historyInfo['contact'],
                    'question_id' => $historyInfo['question_id'],
                ];
                if ($historyInfo['date1'] != '') {
                    $resp['me_wants_date'] = '我方有推进意愿的时间（年月日）'.$historyInfo['date1'];
                }
            }
            if ($table == 'docs_works') {
                $resp = [
                    'num_sn' => $infoMe['num_sn'],
                    'question_msg' => $historyInfo['person_fix_msg'],
                    'is_get_profit' => $infoMe['me_is_getprofit'], //我方做该事件是否可以获得利益
                    'me_wants' => $infoMe['me_work_idea'], //我方推进意愿 zixun_wants
                    'ta_idea' => '', //另一方对我的想法 ta ke_zhu_idea
                    'ta_xinli' => $infoMe['cm_idea_for_me'], //另一方对于该事件此时的心理活动 ta zixun_xinli
                    'ta_wants' => $infoTa['me_work_idea'], //对方增加事件内容一 ta zixun_wants
                    //年：月：日：
                     'year_good' => implode('、', $fInfo['yearGood']),
                    'month_good' => implode('、', $fInfo['monthGood']),
                    'day_good' => implode('、', $fInfo['dayGood']),
                     'easy' => $fInfo['easy'],
                    'date1' => $historyInfo['date1'],
                    'startenddate' => $startenddate1, //时间区间预测
                    'me_wants_date' => '我方有推进意愿的时间（年月日）'.$historyInfo['result_day'], //对方增加事件内容二  我方有推进意愿的时间（年月日）
                    'ta_xintai' => $infoTa['me_xintai'], //客方心态 ta zixun_xintai
                    'me_xintai' => $infoMe['me_xintai'], //我方的心态 zixun_xintai
                    'things_degree' => $infoMe['me_work_things_degree'], //该事件总体推进难易度 things_degree
                    'me_xinli' => $infoMe['me_xinli'], //我方对于该事件此时的心理活动 zixun_xinli
                    'rate' => $historyInfo['rate'], //指定风险管理推送频率
                    'solution' => $infoMe['cm_hope_me'], //解决方案
                    'is_show_time_res' => $historyInfo['is_show_time_res'],
                    'me_name' => empty($historyInfo['me_name']) ? '我方' : $historyInfo['me_name'],
                    'ta_name' => empty($historyInfo['ta_name']) ? '另一方' : $historyInfo['ta_name'],
                    'contact' => $historyInfo['contact'],
                    'question_id' => $historyInfo['question_id'],
                ];
                if ($historyInfo['date1'] != '') {
                    $resp['me_wants_date'] = '我方有推进意愿的时间（年月日）'.$historyInfo['date1'];
                }
            }
            if ($table == 'docs_emotion') {
                $resp = [
                    'num_sn' => $infoMe['num_sn'],
                    'question_msg' => $historyInfo['person_fix_msg'],
                    'is_get_profit' => '', //我方做该事件是否可以获得利益
                    'me_wants' => $infoMe['me_tuijin'], //我方推进意愿 zixun_wants
                    'ta_idea' => '', //另一方对我的想法 ta ke_zhu_idea
                    'ta_xinli' => $infoMe['ta_wants'], //另一方对于该事件此时的心理活动 ta zixun_xinli  $infoTa['me_xinli']
                    'ta_wants' => $infoTa['me_tuijin'], //对方增加事件内容一 ta zixun_wants
                    //年：月：日：
                    'year_good' => implode('、', $fInfo['yearGood']),
                    'month_good' => implode('、', $fInfo['monthGood']),
                    'day_good' => implode('、', $fInfo['dayGood']),
                    'easy' => $fInfo['easy'],
                    'date1' => $historyInfo['date1'],
                    'startenddate' => $startenddate1, //时间区间预测
                    'me_wants_date' => '我方有推进意愿的时间（年月日）'.$historyInfo['result_day'], //对方增加事件内容二  我方有推进意愿的时间（年月日）
                    'ta_xintai' => $infoTa['me_xintai'], //客方心态 ta zixun_xintai
                    'me_xintai' => $infoMe['me_xintai'], //我方的心态 zixun_xintai
                    'things_degree' => $infoMe['me_tuijin_degree'], //该事件总体推进难易度 things_degree
                    'me_xinli' => $infoMe['me_xinli'], //我方对于该事件此时的心理活动 zixun_xinli
                    'rate' => $historyInfo['rate'], //指定风险管理推送频率
                    'solution' => $infoMe['ta_hope_me'], //解决方案
                    'is_show_time_res' => $historyInfo['is_show_time_res'],
                    'me_name' => empty($historyInfo['me_name']) ? '我方' : $historyInfo['me_name'],
                    'ta_name' => empty($historyInfo['ta_name']) ? '另一方' : $historyInfo['ta_name'],
                    'contact' => $historyInfo['contact'],
                    'question_id' => $historyInfo['question_id'],
                ];
                if ($historyInfo['date1'] != '') {
                    $resp['me_wants_date'] = '我方有推进意愿的时间（年月日）'.$historyInfo['date1'];
                }
            }
            //健康预测
            if ($table == 'health') {
                if ($historyInfo['question_id'] == 59) {
                    $startenddate = $this->_getDate($num_sn, 1);
                }
                $resp = [
                   'num_sn' => $infoMe['num_sn'],
                    'question_msg' => $historyInfo['person_fix_msg'],
                    'ta_xinli' => $infoMe['customer_xinli'], //另一方对于该事件此时的心理活动 ta zixun_xinli
                    //年：月：日：
                     'year_good' => implode('、', $fInfo['yearGood']),
                    'month_good' => implode('、', $fInfo['monthGood']),
                    'day_good' => implode('、', $fInfo['dayGood']),
                    'easy' => $fInfo['easy'],
                    'date1' => $historyInfo['date1'], //咨询日期
                    'startenddate' => $startenddate, //时间区间预测
                    //对方增加事件内容二  我方有推进意愿的时间（年月日）
                    'ta_xintai' => $infoTa['customer_xintai'], //客方心态 ta zixun_xintai
                    'is_get_profit' => $infoMe['customer_xinli'], //我方的心态 me_xintai
                    'me_xintai' => $infoMe['zixun_xintai'], //我方的心态 me_xintai
                    'things_degree' => $infoMe['things_degree'], //该事件总体推进难易度 things_degree
                    'me_xinli' => $infoMe['zixun_xinli'], //我方对于该事件此时的心理活动 zixun_xinli
                    'solution' => $infoMe['solution'], //解决方案
                    'is_show_time_res' => $historyInfo['is_show_time_res'],
                    'me_name' => empty($historyInfo['me_name']) ? '我方' : $historyInfo['me_name'],
                    'ta_name' => empty($historyInfo['ta_name']) ? '另一方' : $historyInfo['ta_name'],
                    'contact' => $historyInfo['contact'],
                    'question_id' => $historyInfo['question_id'],
                    'health_status' => $infoMe['health_status'], //健康状态
                    'me_wants' => $infoMe['patient_psychology'], //时间
                    'ta_idea' => $infoMe['times'], //病人心理
                    'ta_wants' => '', //病人心理
                    'me_wants_date' => '',
                ];
                if ($historyInfo['date1'] != '') {
                    $resp['me_wants_date'] = '我方有推进意愿的时间（年月日）'.$historyInfo['date1'];
                }
            }
            foreach ($resp as $kItem => $kVal) {
                // $resp['ta_name'] = substr_replace($resp['ta_name'], '****', 3, 4);
                $resp[$kItem] = str_replace('\n', "\n", $resp[$kItem]);
            }
            $result_title = Db::name('result_title')->field('*')->find();

            foreach ($result_title as $kItem => $kVal) {
                $kVal = str_replace('{{me}}', $resp['me_name'], $kVal);
                $result_title[$kItem] = str_replace('{{ta}}', $resp['ta_name'], $kVal);
            }
            $resp['result_title'] = $result_title;

            //当时股市问题时回显用户conact 字段
            if ($historyInfo['contact'] == '1') {
                $resp['contact_text'] = '是';
            } elseif ($historyInfo['contact'] == '2') {
                $resp['contact_text'] = '股市';
            } else {
                $resp['contact_text'] = '否';
            }

            $last_num = substr($infoMe['num_sn'], -1);
            $resp['last_num_text'] = '不建议';
            if ($last_num == 1) {
                $resp['last_num_text'] = '可以用';
            }

            //如果是股市单独判断
            if (in_array($historyInfo['question_id'], [34, 35, 55, 56]) && $historyInfo['contact'] == 2) {
                if ($last_num == 1 && $easy == 1) {
                    $resp['last_num_text'] = '可以用';
                }
            }
            // 新增中医诊断及体检==question_id: 83>>把他换成已有的75, 小程序就不改代码
            if ($resp['question_id'] == 83) {
                $resp['question_id'] = 75;
            }

            $resp['q_flag'] = 1;
            $resp['g_flag'] = 1; //股市判断日期是否显示标志
            $resp['date_text'] = '容易实现';
            $resp['hui'] = 1;
            $resp['date_diff'] = '容易实现';
            // 增加是否是特殊编号组的判断标志
            $resp['is_special'] = 0;
            // 2024-10-06, 新要求,所有提问 都展示 难打成事件, 所以这个标志不用
            $tempSn = substr($num_sn, 0, -1);

            // 有年月日的, 如果是月份, 看月份与编号相冲不
            $resp['is_date_coflict'] = $resp['is_month_coflict'] = 0;
            // 当前提问,是否以月 单位结束
            $resp['is_month'] = 0;

            if ($resp['date1'] != '无' && !empty($resp['date1'])) {
                $parts = explode('-', $resp['date1']);
                // 单日期2024-01-01
                if (!empty($parts[2])) {
                    $numberSn = $this->_getNumsnNumber($num_sn);
                    //TODO: 日期的 地支属性算法有bug,需解决.
                    $suitNumSnArr = $this->_getSuitDateWuXing($parts[0], $parts[1], $parts[2]);
                    // echo $numberSn;dump($suitNumSnArr);exit;
                    if (in_array($numberSn, $suitNumSnArr)) {
                        $resp['is_date_coflict'] = 1;
                    }
                }
                // 月份: $parts[1]
                if (!empty($parts[1]) && count($parts) == 2) {
                    $resp['is_month'] = 1;
                    $numberSn = $this->_getNumsnNumber($num_sn);
                    $suitNumSnArr = $this->_calSuitNumsnArr($parts[1], 2);

                    if (in_array($numberSn, $suitNumSnArr)) {
                        $resp['is_month_coflict'] = 1;
                    }
                }
            }

            if (in_array($tempSn, config('app.special_group'))) {
                $resp['is_special'] = 1;
            }
            // 难达成事件, 根据 编号的属性 与 2024~2043 的属性, 相生相克来区分
            // 相生==会, 相克==不会
            // private function _yuce($me, $date = '') 里面把 所有年的, 属性全部列出来了
            // 0: 相克. 1: 相生
            // 2024-2043段,不是火/土, 则是 0: 不会|不易实现. 1:会|容易实现
            // 特殊编号, 直接就是 不会|不易实现
            $resp['is_coflict'] = $this->_getNumsnAttr($num_sn);
            // 较难达成 事件. 说白了, 属性相生 放宽点. 金 生 金/水
            // 0: 相克. 1: 相生
            $resp['is_second_coflict'] = 0;
            //TODO:
            $resp['fast'] = $resp['slow'] = $resp['latest'] = 0;
            // 获取当前随机编号, 括号中的数字
            // 如果是 单日期的.
            if (!empty($historyInfo['date1'])) {
                $answerYear = substr($historyInfo['date1'], 0, 4);
                $numberSn = $this->_getNumsnNumber($num_sn);
                // 与当前提问年,相匹配的 五行属性的编号
                $suitNumSnArr = $this->_calSuitNumsnArr($answerYear);
                // 极难事件,用这个匹配
                if (in_array($numberSn, $suitNumSnArr)) {
                    $resp['is_second_coflict'] = 1;
                }
                //TODO: 指定（年月日）常规的编号，返回的如果是 不会 的时候，还能直接展示成 最快 慢点 最晚
            }

            // 针对有日期的问题
            if ($historyInfo['date1'] && $historyInfo['contact'] == 0) {
                //有年月日
                //   $resp['hui'] = 1;
                $dateStr = explode('-', $historyInfo['date1']);
                $startNum = substr($num_sn, 0, 2); //开头两数字
                $endMum = substr($num_sn, 7, 1); //括号里面的数
                $yearNum = substr($num_sn, 0, -1);

                //年否
                if ((in_array($yearNum, config('app.special_group'))) && count($dateStr) == 1 && ($dateStr[0] >= 2024 && $dateStr[0] <= 2043)) {
                    $resp['date_text'] = '容易实现';
                } elseif (count($dateStr) == 1 && ($dateStr[0] >= 2024 && $dateStr[0] <= 2043)) {
                    $resp['hui'] = 0;
                    $resp['easy'] = 0;
                }

                if ((in_array($startNum, [63, 86, 76, 68, 67, 76, 86, 14, 15, 24, 25, 31, 32, 47, 57, 48, 58, 64.65, 38, 37]) && in_array($endMum, [1, 2, 3]))
                  || (in_array($startNum, [36, 41, 51, 42, 52, 13, 23, 74, 75, 84, 85, 46, 56, 87, 73]) && in_array($endMum, [4, 5, 6]))) {
                } else {
                    //日否
                    if (count($dateStr) == 3) {
                        $resp['easy'] = $fInfo['yuce']['ymd'][1];
                        //问日  以月的结果 否返回 最快最慢数字
                        if (!$resp['easy']) {
                            $resp['date1'] = $this->_getDate($num_sn);
                        }
                    }
                    //问月否
                    if (count($dateStr) == 2) {
                        $resp['easy'] = $fInfo['yuce']['ymd'][0];
                        if (!$resp['easy']) {
                            $resp['date1'] = $this->_getDate($num_sn);
                        }
                    }
                }
            } elseif (empty($historyInfo['date1']) && $historyInfo['contact'] == 0) {
                $resp['date_diff'] = '不易实现';
            }
            // 较难事件. 0-无,1-会,2-不易实现
            $jiaoDiffRes = $this->_getDiffNumsnAttr($num_sn);
            $reflect = ['无', '容易实现', '不易实现'];
            $resp['jiao_diff_res'] = $reflect[$jiaoDiffRes];
            // contact 1 普通返回 0 特殊编号 2 股市
            if (in_array($historyInfo['question_id'], [34, 35, 55, 56])) {
                if ($historyInfo['contact'] == 2 && $historyInfo['date1'] != '') {
                    if ($last_num == 0) {
                        $resp['g_flag'] = 0;
                    } //如果股票尾号是0 则整体年月日都不展示
                }
                //  $resp['q_flag'] = 0;
                $resp['date_text'] = '容易实现';
                //选否：特殊编号组会+编号尾号1（建议）/0（不建议）。
                if ($historyInfo['contact'] == 0 && $easy == 1) {
                    $startNum = substr($num_sn, 0, 2); //开头两数字
                    $endMum = substr($num_sn, 7, 1); //括号里面的数字
                    if ($last_num == 1) {
                        if (in_array($startNum, [11, 12, 21, 22, 33, 44, 45, 54, 55, 66, 77, 78, 87, 88])
                        || (in_array($startNum, [63, 86, 76, 68, 67, 76, 14, 15, 24, 25, 31, 32, 47, 57, 48, 58]) && in_array($endMum, [1, 2, 3]))
                        || (in_array($startNum, [13, 23, 74, 75, 84, 85, 36, 41, 51, 42, 52]) && in_array($endMum, [4, 5, 6]))) {
                            $resp['last_num_text'] = '建议';
                        }
                    }
                }
                // 常规编号会+编号尾号是1的。选是：常规编号会+编号尾号1（建议）/0（不建议）
                if ($historyInfo['contact'] == 2 && $easy == 1) {
                    if ($last_num == 1) {
                        $resp['last_num_text'] = '建议';
                    }
                }
                //单独处理股票建议的年月日 $startenddate

                // $resp['startenddate'] = '';
                $respDay = [];
                $dayArr = $this->_date($historyInfo['input_data']);
                if ($dayArr) {
                    foreach ($dayArr as $datei) {
                        if (in_array($datei, $startenddate)) {
                            $respDay[] = $datei;
                        }
                    }
                }
            } else {
                if ($startdate == '') {
                    if ($historyInfo['contact'] == 0 && $easy == 1) {
                        $startNum = substr($num_sn, 0, 2); //开头两数字
                    $endMum = substr($num_sn, 7, 1); //括号里面的数字
                    if ($last_num == 1) {
                        if (in_array($startNum, [11, 12, 21, 22, 33, 44, 45, 54, 55, 66, 77, 78, 87, 88])
                        || (in_array($startNum, [63, 86, 76, 68, 67, 76, 14, 15, 24, 25, 31, 32, 47, 57, 48, 58]) && in_array($endMum, [1, 2, 3]))
                        || (in_array($startNum, [13, 23, 74, 75, 84, 85, 36, 41, 51, 42, 52]) && in_array($endMum, [4, 5, 6]))) {
                            $resp['q_flag'] = 1;
                        }
                    } else {
                        $resp['q_flag'] = 0;
                    }
                    }
                }
            }
            //是否付费
            $resp['resolve_pay'] = $historyInfo['resolve_pay'];
            $userMonth = Db::name('member')->where(['phone' => $phone])->field('month_day,works_month_nums,emotion_month_nums,pr_month_nums,group_month_nums,stu_once_nums,stu_month_nums,medical_once_nums')->find();

            //如果未支付查询是否开通月卡===有开通月卡不收费
            if ($resp['resolve_pay'] == 0) {
                //判断是否有月卡
                switch ($historyInfo['result_type']) {
                    case 1:
                        if ($userMonth['month_day'] > 0) {
                            $resp['resolve_pay'] = 1;
                        }
                        break;
                    case 2:
                        if ($userMonth['works_month_nums'] > 0) {
                            $resp['resolve_pay'] = 1;
                        }
                        break;
                    case 3:
                        if ($userMonth['emotion_month_nums'] > 0) {
                            $resp['resolve_pay'] = 1;
                        }
                        break;
                    case 4:
                        if ($userMonth['pr_month_nums'] > 0) {
                            $resp['resolve_pay'] = 1;
                        }
                        break;
                    case 5:
                        if ($userMonth['group_month_nums'] > 0) {
                            $resp['resolve_pay'] = 1;
                        }
                        break;
                    case 6:
                        if ($userMonth['stu_month_nums'] > 0) {
                            $resp['resolve_pay'] = 1;
                        }
                        break;
                }
            }
            if ($type == '19') {
                $resp['is_show_time_res'] = 1; //健康状态不显示年月日
                // 中医健康板块下, 有体验次数的情况 得消耗1次
                if ($userMonth['medical_once_nums'] >= 1) {
                    Db::name('member')->where(['phone' => $phone])->setDec('medical_once_nums');
                }
            }

            $resp['audit'] = $this->audit && $isIos ? 1 : 0;
            $resp['ff'] = '付费';
            $resp['time_pay'] = 1;
            $resp['isHidden'] = $isHidden;
            //页面有无利益颜色
            $resp['last_num_css'] = 'green_1';
            if ($resp['last_num_text'] == '可以用') {
                $resp['last_num_css'] = 'green_2';
            }
            //查询频率开关
            $resp['rate_value'] = Db::name('config')->where(['id' => 22])->value('value');
            //二维码
            $resp['qrcode'] = 'https://docs.spacetimesc.com/static/qrcode/'.$historyInfo['person_menu_id'].'-'.$historyInfo['person_menu_item_id'].'.jpg';
            $resp['year_easy'] = '';

            if ($resp['year_good']) {
                // 取消换行符
                $resp['year_easy'] = $this->_getDate($resp['num_sn']);
                $resp['year_easy'] = str_replace("\n", ',', $resp['year_easy']);
            }

            $res['code'] = 0;
            // 只有健康 栏目才展示 天
            // $table = 'health';
            if ($table == 'health') {
                $resp['year_easy'] = $this->_getDate($resp['num_sn'], 1);
                $resp['year_easy'] = str_replace("\n", ',', $resp['year_easy']);
            // file_put_contents('/tmp/debug.log', $resp['year_easy'], FILE_APPEND);
            } else {
                $resp['year_easy'] = $this->_getDate($resp['num_sn'], 0);
                $resp['year_easy'] = str_replace("\n", ',', $resp['year_easy']);
                // file_put_contents('/tmp/debug.log', $resp['year_easy'], FILE_APPEND);
            }
            // 替换 中文
            $resp['year_good'] = str_replace('、', ',', $resp['year_good']);
            $resp['month_good'] = str_replace('、', ',', $resp['month_good']);
            $resp['day_good'] = str_replace('、', ',', $resp['day_good']);
            // 需要单独针对 $historyId=152232, 不展示某一块
            $resp['deal_152232'] = ($historyId == 152232 || $historyInfo['person_menu_item_id'] == 83) ? 1 : 0;
            // 新增加的 三个健康板块,页面需要单独做显示
            $resp['is_special_medical'] = 0;
            // 中医诊断及体检下面的都不需要 展示ta_idea那种小item
            if (in_array($historyInfo['question_id'], config('app.medical_ids'))) {
                $resp['ta_idea_list'] = explode(',', $resp['year_easy']);
                $resp['is_special_medical'] = 1;
            }
            // 加粗 health_status 中的当前
            if (!empty($resp['health_status'])) {
                $resp['health_status'] = '健康状态: '.$resp['health_status'];
            }
            // if (!empty($resp['health_status'])) $resp['health_status'] = $this->_replaceTwoWords($resp['health_status'], '当', '前');
            $res['data'] = $resp;

            return json($res);
        } catch (\Throwable $th) {
            $res['code'] = 1;
            $res['msg'] = $th->getMessage();

            return json($res);
        }
    }

    // 获取最快慢点，最晚天数
    private function _getDate($num_sn, $isBringDay = 0)
    {
        $fast_time = $slow_time = $late_time = 0;
        //当编号第1位和第5位数字相同时，最快时间=第6位数字，慢点时间=第1，2，6位之和/2，最晚时间=第1，2，6位之和。
        if ($num_sn[0] == $num_sn[4]) {
            $fast_time = $num_sn[5];
            $slow_time = ($num_sn[0] + $num_sn[1] + $num_sn[5]) / 2;
            $late_time = $num_sn[0] + $num_sn[1] + $num_sn[5];
        } elseif ($num_sn[1] == $num_sn[5]) {
            //当编号第2位和第6位数字相同时，最快时间=第5位数字，慢点时间=第1，2，5位之和/2，最晚时间=第1，2，5位之和。
            $fast_time = $num_sn[4];
            $slow_time = ($num_sn[0] + $num_sn[1] + $num_sn[4]) / 2;
            $late_time = $num_sn[0] + $num_sn[1] + $num_sn[4];
        } elseif ($slow_time < $fast_time) {
            //特殊情况 ，如果慢点时间<最快时间的时候，最小值为最快时间。
            $late_time = $fast_time;
        }

        $startenddate = ['最快 '.$fast_time, '慢点 '.$slow_time, '最晚 '.$late_time];
        // 除开健康其他的都不展示 天这个 时间单位
        if ($isBringDay) {
            $startenddate = ['最快 '.$fast_time.' 天', '慢点 '.$slow_time.' 天', '最晚 '.$late_time.' 天'];
        }
        // return $startenddate;
        return implode("\n", $startenddate);
    }

    //获取ta的值
    private function _getTa($historyInfo)
    {
        $meResultId = $historyInfo['result_id'];
        $taResultId = $historyInfo['ta_result_id'];

        // 用户提问信息
        $personTpl = $historyInfo['person_fix_msg'];

        $type = $historyInfo['person_menu_id'];
        $table = 'docs_latest'; ////项目预测
        if ($type == '2' || $type == '8') {
            $table = 'docs_works'; //工作事业
        }
        if ($type == '3' || $type == '9') {
            $table = 'docs_emotion'; //工作事业
        }

        $infoMe = Db::name($table)->field('*')->where(['id' => $meResultId])->find();

        $infoTa = Db::name($table)->field('*')->where(['id' => $taResultId])->find();
        if (empty($infoMe) || empty($infoTa)) {
            throw new Exception('未查询到咨询结果!', 1);
        }

        $num_sn = $infoMe['num_sn'];
        $me = $num_sn[7] > 3 ? $num_sn[1] : $num_sn[0];
        $ta = $num_sn[7] > 3 ? $num_sn[0] : $num_sn[1];
        // print_r($num_sn);exit;
        //使用me的编号进行预测
        if (!empty($historyInfo['me_name']) && empty($historyInfo['ta_name'])) {
            $tmp = $ta;
            $ta = $me;
            $me = $tmp;
        }

        return $ta;
    }

    /**
     *预测日期 $easy的值
     */
    private function _forecastDay($date1, $historyInfo, $ta, $num_sn)
    {
        $yearGood = [];
        $monthGood = [];
        $dayGood = [];
        $day = date('Y-m-d');
        if (!empty($historyInfo['result_day'])) {
            $day = $historyInfo['result_day'];
        }
        if ($historyInfo['is_show_time_res'] != 1 && $historyInfo['contact'] != 1) { //没有建立联系
                $day = date('Y-m-d', strtotime($day) + 30 * 86400); //下月日期预测
        }
        $lenDate1 = strlen($date1);
        if ($lenDate1 == 10) {
            $day = $date1;
        } elseif ($lenDate1 == 7) {
            $day = $date1.'-01';
        } elseif ($lenDate1 == 4) {
            $day = $date1.'-01-01';
        }
        // print_r($ta,$day);exit;
        $yuce = $this->_yuce($ta, $day);
        // dump($yuce);exit;

        foreach ($yuce['years'] as $key => $value) {
            if ($value[2]) {
                $yearGood[] = $value[0];
            }
            if (count($yearGood) >= 4) {
                break;
            }
        }
        foreach ($yuce['months'] as $key => $value) {
            if ($value[2]) {
                $monthGood[] = $value[0];
            }
        }
        foreach ($yuce['days'] as $key => $value) {
            if ($value[2]) {
                $dayGood[] = $value[0];
            }
        }
        // dump($yuce['days']);exit;

        $easy = 0;
        $easyNum = array_sum($yuce['ymd']);
        if ($historyInfo['is_show_time_res'] == 1) { //已知事件结果发生日期
                if ($lenDate1 == 10) {//年月日
                    $easy = $yuce['ymd'][2];
                } elseif ($lenDate1 == 7) {//年月
                    $easy = $yuce['ymd'][1];
                } elseif ($lenDate1 == 4) {//年
                    $easy = $yuce['ymd'][0];
                } else {
                    $easy = $easyNum > 1 ? 1 : 0;
                }
            //新增逻辑2023 10-31
            // 11xxxx，12xxxx，21xxxx，22xxxx，33xxxx，44xxxx，45xxxx，54xxxx，55xxxx，66xxxx，77xxxx，78xxxx，87xxxx，88xxxx；
            // 61/62xxxx（1/2/3），16/12xxxx（4/5/6），18/28/17/27xxxx（1/2/3），81/82/71/72xxxx（4/5/6），34/35xxxx（1/2/3），
            //  43/53xxxx（4/5/6），46/56xxxx（1/2/3），64/65xxxx（4/5/6），83/73xxxx（4/5/6），38/37xxxx（1/2/3）
            if ($historyInfo['contact'] == 0 && $easy == 1) {
                $startNum = substr($num_sn, 0, 2); //开头两数字
                    $endMum = substr($num_sn, 7, 1); //括号里面的数字

                    if (in_array($startNum, [11, 12, 21, 22, 33, 44, 45, 54, 55, 66, 77, 78, 87, 88])
                        || (in_array($startNum, [63, 86, 76, 68, 67, 76, 14, 15, 24, 25, 31, 32, 47, 57, 48, 58]) && in_array($endMum, [1, 2, 3]))
                        || (in_array($startNum, [13, 23, 74, 75, 84, 85, 36, 41, 51, 42, 52]) && in_array($endMum, [4, 5, 6]))) {
                        $easy = 1;
                    } else {
                        $easy = 0;
                    }
            }
        } else { //无具体出结果日期事件
            $easy = $easyNum > 1 ? 1 : 0;
        }

        return [
                'easy' => $easy,
                'yearGood' => $yearGood,
                'monthGood' => $monthGood,
                'dayGood' => $dayGood,
                'yuce' => $yuce,
                ];
    }

    //自动提问javascript:;
    public function autoQuestion()
    {
        $redis = new Redis();
        $historyId = $redis->handler()->rpop('autoList');
        // $historyId = 150938;
        if ($historyId) {
            $historyInfo = Db::name('new_user_question_history')->field('*')->where(['id' => $historyId])->find();

            $inputData = $historyInfo['input_data'];

            $data = Db::name('question')->field('*')->where(['id' => $historyInfo['question_id']])->find();
            if (empty($data)) {
                trace('预测失败 question_id 不存在', 'info');
            }

            $type = $data['answer_type'];
            $input_data = [];
            $me_name = ''; //我方名称

            //预测日期
            $result_day = date('Y-m-d');

            // 随机取一个. 如果是: 项目预测:1 + 公关审核:4 + 公司用户:5
            if ($type == 1 || $type == 4 || $type == 5) {
                $typeIds = Db::name('docs_latest')->field('id')->select();
            }
            // 随机取一个. 如果是: 工作事业选择: 2
            if ($type == 2 || $type == 6) {
                $typeIds = Db::name('docs_works')->field('id')->select();
            }
            // 随机取一个. 如果是: 情感咨询选择: 3
            if ($type == 3) {
                $typeIds = Db::name('docs_emotion')->field('id')->select();
            }

            $typeIdsArr = array_column($typeIds, 'id');
            //股市
            if (in_array($historyInfo['question_id'], [34, 35])) {
                $dayArr = $this->_date($inputData);
                //入库
                if (count($dayArr) > 0) {
                    $inputData = json_decode($inputData, true);
                    $ta_name = $inputData[3][1];
                    foreach ($dayArr as $d) {
                        // 从数组里面随机取出一个
                        $key = array_rand($typeIdsArr, 2);
                        if (empty($key)) {
                            trace('预测失败', 'info');
                        }
                        $historyInfo['person_fix_msg'] = $d.' '.$inputData[2][1].',会'.$inputData[3][1].'吗?';

                        $result_id = $typeIdsArr[$key[0]];
                        $ta_result_id = $typeIdsArr[$key[1]];

                        //   [["title1","我"],["date1","2024-01-16"],["title2","有好运"]]
                        //  json_encode($input_data, JSON_UNESCAPED_UNICODE),
                        $input_data[] = [$inputData[2][0], $inputData[2][1]];
                        $input_data[] = ['date1', $d];
                        $input_data[] = [$inputData[3][0], $inputData[3][1]];
                        $historyInfo['input_data'] = json_encode($input_data, JSON_UNESCAPED_UNICODE);
                        $historyInfo['date1'] = $inputData[0][1];
                        $historyInfo['is_show_time_res'] = 1;

                        unset($historyInfo['id']);
                        $historyInfo['ta_name'] = $ta_name;
                        $historyInfo['result_day'] = $result_day;

                        $historyInfo['ta_result_id'] = $ta_result_id;
                        $historyInfo['add_time'] = date('Y-m-d H:i:s', time());
                        $historyInfo['date1'] = $d;
                        $historyInfo['result_id'] = $result_id;
                        $historyInfo['resolve_pay'] = 0;
                        // $historyInfo['time_pay'] = 0;
                        $historyInfo['pid'] = $historyId;

                        $historyIdt = Db::name('new_user_question_history')->insertGetId($historyInfo);
                        $input_data = [];
                        if (!$historyIdt) {
                            trace('预测失败 入库失败', 'info');
                        }
                    }
                }
            }

            //股市带区间
            if (in_array($historyInfo['question_id'], [55, 56])) {
                //入库
                $dayArr = $this->_date($inputData);
                $inputData = json_decode($inputData, true);
                $numArr = $this->_num($inputData[3][1], $inputData[4][1]);
                $ta_name = $inputData[2][1];
                foreach ($dayArr as $day) {
                    foreach ($numArr as $d) {
                        // 从数组里面随机取出一个
                        $key = array_rand($typeIdsArr, 2);
                        if (empty($key)) {
                            trace('预测失败', 'info');
                        }
                        $historyInfo['person_fix_msg'] = $day.' '.$ta_name.',会到'.$d.'吗';

                        $result_id = $typeIdsArr[$key[0]];
                        $ta_result_id = $typeIdsArr[$key[1]];

                        $input_data[] = ['date1', $day];
                        $input_data[] = [$inputData[2][0], $inputData[2][1]];
                        $input_data[] = [$inputData[3][0], $inputData[3][1]];
                        $input_data[] = [$inputData[4][0], $inputData[4][1]];
                        $historyInfo['input_data'] = json_encode($input_data, JSON_UNESCAPED_UNICODE);

                        unset($historyInfo['id']);
                        $historyInfo['ta_name'] = $ta_name;
                        $historyInfo['ta_name1'] = $d;
                        $historyInfo['result_day'] = $result_day;

                        $historyInfo['ta_result_id'] = $ta_result_id;
                        $historyInfo['add_time'] = date('Y-m-d H:i:s', time());
                        $historyInfo['result_id'] = $result_id;
                        $historyInfo['resolve_pay'] = 0;
                        // $historyInfo['time_pay'] = 0;
                        $historyInfo['is_show_time_res'] = 1;
                        $historyInfo['date1'] = $day;
                        $historyInfo['pid'] = $historyId;

                        //   dump($historyInfo);exit;
                        $historyIdt = Db::name('new_user_question_history')->insertGetId($historyInfo);
                        $input_data = [];
                        if (!$historyIdt) {
                            trace('预测失败 入库失败', 'info');
                        }
                    }
                }
            }
        }
    }

    public function getNum()
    {
        $min = input('min', 0);
        $max = input('max', 0);
        $numArr = $this->_num($min, $max);
        $res['code'] = 0;
        $res['data'] = count($numArr);

        return json($res);
    }

    //返回数字区间
    private function _num($min, $max)
    {
        $numArr = [];
        if ($min < 500) {
            for ($i = $min; $i <= $max; ++$i) {
                $numArr[] = $i;
            }
        }
        if ($min >= 500 && $min < 1000) {
            for ($i = $min; $i <= $max; $i += 10) {
                $numArr[] = $i;
            }
        }
        if ($min >= 1000) {
            for ($i = $min; $i <= $max; $i += 50) {
                $numArr[] = $i;
            }
        }

        return $numArr;
    }

    //根据时间返回中间中间所有的时间
    private function _date($inputData)
    {
        $inputData = json_decode($inputData, true);
        $startDate = $inputData[0][1];
        $endDate = $inputData[1][1];
        $startTime = explode('-', $startDate);
        $endTime = explode('-', $endDate);
        $dayArr = [];
        //取得递增年
        if (count($startTime) == 1) {
            $startDateUnix = strtotime($startDate.'-01-01');
            $endDateUnix = strtotime($endDate.'-01-01');
            for ($startDateUnix; $startDateUnix <= $endDateUnix; $startDateUnix = strtotime('+1 year', $startDateUnix)) {
                $dayArr[] = date('Y', $startDateUnix);
            }
            //删除第一个元素，因为已经提问了
            // 	array_shift($dayArr);
        }
        $startDateUnix = strtotime($startDate);
        $endDateUnix = strtotime($endDate);
        //取得递增月
        if (count($startTime) == 2) {
            for ($startDateUnix; $startDateUnix <= $endDateUnix; $startDateUnix = strtotime('+1 month', $startDateUnix)) {
                $dayArr[] = date('Y-m', $startDateUnix);
            }
            // 	array_shift($dayArr);
        }
        //取得递增日
        if (count($startTime) == 3) {
            for ($startDateUnix; $startDateUnix <= $endDateUnix; $startDateUnix = strtotime('+1 day', $startDateUnix)) {
                $dayArr[] = date('Y-m-d', $startDateUnix);
            }
            // 	array_shift($dayArr);
        }

        return $dayArr;
    }

    /**
     * 获取预测信息.
     *
     * @return void
     */
    public function getPredictsall()
    {
        $res = ['code' => 1, 'data' => [], 'msg' => ''];
        try {
            // 个人 咨询,历史记录
            $historyId = input('history_id', '0');
            // print_r($historyId);exit;
            if (empty($historyId)) {
                throw new Exception('咨询记录ID不能为空!', 1);
            }
            // 根据 $historyId, 得出它咨询所 得到的答案ID
            $historyInfo = Db::name('new_user_question_history')->field('*')->where(['id' => $historyId])->find();
            // print_r($historyInfo);exit;
            if (empty($historyInfo)) {
                throw new Exception('未查询到咨询结果!', 1);
            }
            // echo(1);exit;
            //v3 老数据兼容
            if (in_array($historyInfo['person_menu_id'], [1, 2, 3, 4])) {
                $type = $historyInfo['person_menu_id'];
                $itypes = $historyInfo['person_menu_item_id'];
                $resultId = $historyInfo['result_id'];

                // 咨询配置
                $personConf = config('personal_consult_tmpl');
                // 根据 大小菜单, 确认用户提问信息
                $personTpl = isset($personConf[$type]['items'][$itypes]) ? $personConf[$type]['items'][$itypes] : '';
                if ($personTpl != '') {
                    // 如果是 工作事业选择
                    if ($itypes == 4) {
                        $personTpl = sprintf($personTpl, $historyInfo['person_fix_msg'], $historyInfo['person_job']);
                    }
                    // 非工作事业选择
                    if ($itypes != 4) {
                        $personTpl = sprintf($personTpl, $historyInfo['person_fix_msg']);
                    }
                }

                $info = [];
                // 随机取一个. 如果是: 项目预测: 1 + 公关审核
                if ($type == 1 || $type == 4) {
                    $info = Db::name('docs_latest')->field('*')->where(['id' => $resultId])->find();
                }
                // 随机取一个. 如果是: 工作事业选择: 2
                if ($type == 2) {
                    $info = Db::name('docs_works')->field('*')->where(['id' => $resultId])->find();
                }
                // 随机取一个. 如果是: 情感咨询选择: 3
                if ($type == 3) {
                    $info = Db::name('docs_emotion')->field('*')->where(['id' => $resultId])->find();
                }
                if (empty($info)) {
                    throw new Exception('未查询到咨询结果!', 1);
                }
                // 循环数据里面的 每个 value.替换 \n为 <br/>
                foreach ($info as $kItem => $kVal) {
                    $info[$kItem] = str_replace('\n', '<br/>', $info[$kItem]);
                }

                $info['is_show_time_res'] = 1;
                $info['person_tpl'] = $personTpl;
                $res['code'] = 0;
                $res['data'] = $info;

                return json($res);
            }

            //v4 新数据逻辑
            $meResultId = $historyInfo['result_id'];
            $taResultId = $historyInfo['ta_result_id'];
            // 用户提问信息
            $personTpl = $historyInfo['person_fix_msg'];

            $type = $historyInfo['person_menu_id'];
            $table = 'docs_latest'; ////项目预测
            if ($type == '2' || $type == '8') {
                $table = 'docs_works'; //工作事业
            }
            if ($type == '3' || $type == '9') {
                $table = 'docs_emotion'; //工作事业
            }
            $infoMe = Db::name($table)->field('*')->where(['id' => $meResultId])->find();

            $infoTa = Db::name($table)->field('*')->where(['id' => $taResultId])->find();
            if (empty($infoMe) || empty($infoTa)) {
                throw new Exception('未查询到咨询结果!', 1);
            }

            $num_sn = $infoMe['num_sn'];
            $me = $num_sn[7] > 3 ? $num_sn[1] : $num_sn[0];
            $ta = $num_sn[7] > 3 ? $num_sn[0] : $num_sn[1];
            // print_r($num_sn);exit;
            //使用me的编号进行预测
            if (!empty($historyInfo['me_name']) && empty($historyInfo['ta_name'])) {
                $tmp = $ta;
                $ta = $me;
                $me = $tmp;
            }
            $day = date('Y-m-d');
            if (!empty($historyInfo['result_day'])) {
                $day = $historyInfo['result_day'];
            }

            if ($historyInfo['is_show_time_res'] != 1 && $historyInfo['contact'] != 1) { //没有建立联系
                $day = date('Y-m-d', strtotime($day) + 30 * 86400); //下月日期预测
            }

            //判断编码是否与日期和极端数字匹配
            $cd = substr($num_sn, 0, 2);
            $anq = [11, 12, 21, 22, 33, 44, 45, 54, 55, 66, 77, 78, 87, 88];
            //存在进下一步匹配
            if ($historyInfo['date1'] != '') {
                $times = $historyInfo['date1'];
                $timeslist = explode('-', $times);
                if (in_array($cd, $timeslist)) {
                    if ($historyInfo['contact'] == 0) {
                        if (in_array($cd, $anq)) {
                            $day = date('Y-m-d', strtotime($day)); //下月日期预测
                        }
                        //   else{
                        //     //$day = date('Y-m-d', strtotime($day) + 30 * 86400); //下月日期预测
                        //     throw new Exception("暂无结果!", 1);
                        //  }
                    }
                    // else{
                    //      $day = date('Y-m-d', strtotime($day) + 30 * 86400); //下月日期预测
                    // }
                }
            }
            //年月日咨询日期
            $date1 = $historyInfo['date1'];
            $lenDate1 = strlen($date1);
            if ($lenDate1 == 10) {
                $day = $date1;
            } elseif ($lenDate1 == 7) {
                $day = $date1.'-01';
            } elseif ($lenDate1 == 4) {
                $day = $date1.'-01-01';
            }
            // print_r($ta,$day);exit;
            $yuce = $this->_yuce($ta, $day);
            // print_r($yuce);exit;
            $yearGood = [];
            $monthGood = [];
            $dayGood = [];
            foreach ($yuce['years'] as $key => $value) {
                if ($value[2]) {
                    $yearGood[] = $value[0];
                }
                if (count($yearGood) >= 4) {
                    break;
                }
            }
            foreach ($yuce['months'] as $key => $value) {
                if ($value[2]) {
                    $monthGood[] = $value[0];
                }
            }
            foreach ($yuce['days'] as $key => $value) {
                if ($value[2]) {
                    $dayGood[] = $value[0];
                }
            }
            $easyNum = array_sum($yuce['ymd']);
            if ($historyInfo['is_show_time_res'] == 1) { //已知事件结果发生日期
                if ($lenDate1 == 10) {//年月日
                    $easy = $yuce['ymd'][2];
                } elseif ($lenDate1 == 7) {//年月
                    $easy = $yuce['ymd'][1];
                } elseif ($lenDate1 == 4) {//年
                    $easy = $yuce['ymd'][0];
                } else {
                    $easy = $easyNum > 1 ? 1 : 0;
                }
            } else { //无具体出结果日期事件
                $easy = $easyNum > 1 ? 1 : 0;
            }

            //startdate--enddate 时间区间预测
            $startdate = '';
            $enddate = '';
            $input_data_arr = json_decode($historyInfo['input_data'], true);
            if (is_array($input_data_arr)) {
                foreach ($input_data_arr as $value) {
                    if ($value[0] == 'startdate') {
                        $startdate = $value[1];
                    }
                    if ($value[0] == 'enddate') {
                        $enddate = $value[1];
                    }
                }
            }
            $startenddate = [];
            if ($startdate != '') {
                $tm = strtotime($startdate);
                $yuce2 = $this->_yuce($ta, $startdate);
                foreach ($yuce2['days'] as $key => $value) {
                    $nowDay = date('Y-m-d', $tm + $key * 86400);
                    if ($nowDay > $enddate || count($startenddate) >= 30) {
                        break;
                    }
                    if ($value[2]) {
                        $startenddate[] = $nowDay;
                    }
                }
            }

            //手机号中间4位用****替代
            $historyInfo['user_phone'] = substr_replace($historyInfo['user_phone'], '****', 3, 4);
            //我方 另一方名称处理
            if (!empty($historyInfo['me_name']) && empty($historyInfo['ta_name'])) {
                $historyInfo['ta_name'] = $historyInfo['user_phone'];
            } elseif (empty($historyInfo['me_name'])) {
                $historyInfo['me_name'] = $historyInfo['user_phone'];
            }

            $resp = [];
            if ($table == 'docs_latest') {
                $resp = [
                    'num_sn' => $infoMe['num_sn'],
                    'question_msg' => $historyInfo['person_fix_msg'],
                    'is_get_profit' => $infoMe['is_get_profit'], //我方做该事件是否可以获得利益
                    'me_wants' => $infoMe['zixun_wants'], //我方推进意愿 zixun_wants
                    'ta_idea' => $infoTa['ke_zhu_idea'], //另一方对我的想法 ta ke_zhu_idea
                    'ta_xinli' => $infoTa['zixun_xinli'], //另一方对于该事件此时的心理活动 ta zixun_xinli
                    'ta_wants' => $infoTa['zixun_wants'], //对方增加事件内容一 ta zixun_wants
                    //年：月：日：
                    'year_good' => implode('、', $yearGood),
                    'month_good' => implode('、', $monthGood),
                    'day_good' => implode('、', $dayGood),
                    'easy' => $easy,
                    'date1' => $historyInfo['date1'], //咨询日期
                    'startenddate' => implode("\n", $startenddate), //时间区间预测
                    'me_wants_date' => '我方有推进意愿的时间（年月日）'.$historyInfo['result_day'],
                    //对方增加事件内容二  我方有推进意愿的时间（年月日）
                    'ta_xintai' => $infoTa['zixun_xintai'], //客方心态 ta zixun_xintai
                    'me_xintai' => $infoMe['zixun_xintai'], //我方的心态 zixun_xintai
                    'things_degree' => $infoMe['things_degree'], //该事件总体推进难易度 things_degree
                    'me_xinli' => $infoMe['zixun_xinli'], //我方对于该事件此时的心理活动 zixun_xinli
                    'rate' => $historyInfo['rate'], //指定风险管理推送频率
                    'solution' => $infoMe['solution'], //解决方案
                    'is_show_time_res' => $historyInfo['is_show_time_res'],
                    'me_name' => empty($historyInfo['me_name']) ? '我方' : $historyInfo['me_name'],
                    'ta_name' => empty($historyInfo['ta_name']) ? '另一方' : $historyInfo['ta_name'],
                ];
                if ($historyInfo['date1'] != '') {
                    $resp['me_wants_date'] = '我方有推进意愿的时间（年月日）'.$historyInfo['date1'];
                }
            }
            if ($table == 'docs_works') {
                $resp = [
                    'num_sn' => $infoMe['num_sn'],
                    'question_msg' => $historyInfo['person_fix_msg'],
                    'is_get_profit' => $infoMe['me_is_getprofit'], //我方做该事件是否可以获得利益
                    'me_wants' => $infoMe['me_work_idea'], //我方推进意愿 zixun_wants
                    'ta_idea' => '', //另一方对我的想法 ta ke_zhu_idea
                    'ta_xinli' => $infoTa['me_xinli'], //另一方对于该事件此时的心理活动 ta zixun_xinli
                    'ta_wants' => $infoTa['me_work_idea'], //对方增加事件内容一 ta zixun_wants
                    //年：月：日：
                    'year_good' => implode('、', $yearGood),
                    'month_good' => implode('、', $monthGood),
                    'day_good' => implode('、', $dayGood),
                    'easy' => $easy,
                    'date1' => $historyInfo['date1'],
                    'startenddate' => implode("\n", $startenddate), //时间区间预测
                    'me_wants_date' => '我方有推进意愿的时间（年月日）'.$historyInfo['result_day'], //对方增加事件内容二  我方有推进意愿的时间（年月日）
                    'ta_xintai' => $infoTa['me_xintai'], //客方心态 ta zixun_xintai
                    'me_xintai' => $infoMe['me_xintai'], //我方的心态 zixun_xintai
                    'things_degree' => $infoMe['me_work_things_degree'], //该事件总体推进难易度 things_degree
                    'me_xinli' => $infoMe['me_xinli'], //我方对于该事件此时的心理活动 zixun_xinli
                    'rate' => $historyInfo['rate'], //指定风险管理推送频率
                    'solution' => $infoMe['cm_hope_me'], //解决方案
                    'is_show_time_res' => $historyInfo['is_show_time_res'],
                    'me_name' => empty($historyInfo['me_name']) ? '我方' : $historyInfo['me_name'],
                    'ta_name' => empty($historyInfo['ta_name']) ? '另一方' : $historyInfo['ta_name'],
                ];
                if ($historyInfo['date1'] != '') {
                    $resp['me_wants_date'] = '我方有推进意愿的时间（年月日）'.$historyInfo['date1'];
                }
            }
            if ($table == 'docs_emotion') {
                $resp = [
                    'num_sn' => $infoMe['num_sn'],
                    'question_msg' => $historyInfo['person_fix_msg'],
                    'is_get_profit' => '', //我方做该事件是否可以获得利益
                    'me_wants' => $infoMe['me_tuijin'], //我方推进意愿 zixun_wants
                    'ta_idea' => '', //另一方对我的想法 ta ke_zhu_idea
                    'ta_xinli' => $infoTa['me_xinli'], //另一方对于该事件此时的心理活动 ta zixun_xinli
                    'ta_wants' => $infoTa['me_tuijin'], //对方增加事件内容一 ta zixun_wants
                    //年：月：日：
                    'year_good' => implode('、', $yearGood),
                    'month_good' => implode('、', $monthGood),
                    'day_good' => implode('、', $dayGood),
                    'easy' => $easy,
                    'date1' => $historyInfo['date1'],
                    'startenddate' => implode("\n", $startenddate), //时间区间预测
                    'me_wants_date' => '我方有推进意愿的时间（年月日）'.$historyInfo['result_day'], //对方增加事件内容二  我方有推进意愿的时间（年月日）
                    'ta_xintai' => $infoTa['me_xintai'], //客方心态 ta zixun_xintai
                    'me_xintai' => $infoMe['me_xintai'], //我方的心态 zixun_xintai
                    'things_degree' => $infoMe['me_tuijin_degree'], //该事件总体推进难易度 things_degree
                    'me_xinli' => $infoMe['me_xinli'], //我方对于该事件此时的心理活动 zixun_xinli
                    'rate' => $historyInfo['rate'], //指定风险管理推送频率
                    'solution' => $infoMe['ta_hope_me'], //解决方案
                    'is_show_time_res' => $historyInfo['is_show_time_res'],
                    'me_name' => empty($historyInfo['me_name']) ? '我方' : $historyInfo['me_name'],
                    'ta_name' => empty($historyInfo['ta_name']) ? '另一方' : $historyInfo['ta_name'],
                ];
                if ($historyInfo['date1'] != '') {
                    $resp['me_wants_date'] = '我方有推进意愿的时间（年月日）'.$historyInfo['date1'];
                }
            }

            foreach ($resp as $kItem => $kVal) {
                // $resp['ta_name'] = substr_replace($resp['ta_name'], '****', 3, 4);
                $resp[$kItem] = str_replace('\n', "\n", $resp[$kItem]);
            }

            $result_title = Db::name('result_title')->field('*')->find();
            // if($resp['ta_name']!=''){
            //       $ta_names = substr_replace($resp['ta_name'], '****', 3, 4);
            // }else{
            //       $ta_names = '';
            // }

            foreach ($result_title as $kItem => $kVal) {
                $kVal = str_replace('{{me}}', $resp['me_name'], $kVal);
                $result_title[$kItem] = str_replace('{{ta}}', $resp['ta_name'], $kVal);
            }
            $resp['year_easy'] = '';

            if ($resp['year_good']) {
                // 取消换行符
                $resp['year_easy'] = $this->_getDate($resp['num_sn']);
                $resp['year_easy'] = str_replace("\n", ',', $resp['year_easy']);
            }

            $resp['result_title'] = $result_title;
            $res['code'] = 0;
            $res['data'] = $resp;

            return json($res);
        } catch (\Throwable $th) {
            $res['code'] = 1;
            $res['msg'] = $th->getMessage();

            return json($res);
        }
    }

    public function getPredictall($historyId)
    {
        $res = ['code' => 1, 'data' => [], 'msg' => ''];
        try {
            // 个人 咨询,历史记录
            // $historyId = input('history_id', '0');
            if (empty($historyId)) {
                throw new Exception('咨询记录ID不能为空!', 1);
            }
            // 根据 $historyId, 得出它咨询所 得到的答案ID
            $historyInfo = Db::name('new_user_question_history')->field('*')->where(['id' => $historyId])->find();
            // print_r($historyInfo);exit;
            if (empty($historyInfo)) {
                throw new Exception('未查询到咨询结果!', 1);
            }

            //v3 老数据兼容
            if (in_array($historyInfo['person_menu_id'], [1, 2, 3, 4])) {
                $type = $historyInfo['person_menu_id'];
                $itypes = $historyInfo['person_menu_item_id'];
                $resultId = $historyInfo['result_id'];

                // 咨询配置
                $personConf = config('personal_consult_tmpl');
                // 根据 大小菜单, 确认用户提问信息
                $personTpl = isset($personConf[$type]['items'][$itypes]) ? $personConf[$type]['items'][$itypes] : '';
                if ($personTpl != '') {
                    // 如果是 工作事业选择
                    if ($itypes == 4) {
                        $personTpl = sprintf($personTpl, $historyInfo['person_fix_msg'], $historyInfo['person_job']);
                    }
                    // 非工作事业选择
                    if ($itypes != 4) {
                        $personTpl = sprintf($personTpl, $historyInfo['person_fix_msg']);
                    }
                }

                $info = [];
                // 随机取一个. 如果是: 项目预测: 1 + 公关审核
                if ($type == 1 || $type == 4) {
                    $info = Db::name('docs_latest')->field('*')->where(['id' => $resultId])->find();
                }
                // 随机取一个. 如果是: 工作事业选择: 2
                if ($type == 2) {
                    $info = Db::name('docs_works')->field('*')->where(['id' => $resultId])->find();
                }
                // 随机取一个. 如果是: 情感咨询选择: 3
                if ($type == 3) {
                    $info = Db::name('docs_emotion')->field('*')->where(['id' => $resultId])->find();
                }
                if (empty($info)) {
                    throw new Exception('未查询到咨询结果!', 1);
                }
                // 循环数据里面的 每个 value.替换 \n为 <br/>
                foreach ($info as $kItem => $kVal) {
                    $info[$kItem] = str_replace('\n', '<br/>', $info[$kItem]);
                }

                $info['is_show_time_res'] = 1;
                $info['person_tpl'] = $personTpl;
                $res['code'] = 0;
                $res['data'] = $info;

                return json($res);
            }

            //v4 新数据逻辑
            $meResultId = $historyInfo['result_id'];
            $taResultId = $historyInfo['ta_result_id'];
            // 用户提问信息
            $personTpl = $historyInfo['person_fix_msg'];

            $type = $historyInfo['person_menu_id'];
            $table = 'docs_latest'; ////项目预测
            if ($type == '2' || $type == '8') {
                $table = 'docs_works'; //工作事业
            }
            if ($type == '3' || $type == '9') {
                $table = 'docs_emotion'; //工作事业
            }
            $infoMe = Db::name($table)->field('*')->where(['id' => $meResultId])->find();

            $infoTa = Db::name($table)->field('*')->where(['id' => $taResultId])->find();
            if (empty($infoMe) || empty($infoTa)) {
                throw new Exception('未查询到咨询结果!', 1);
            }

            $num_sn = $infoMe['num_sn'];
            $me = $num_sn[7] > 3 ? $num_sn[1] : $num_sn[0];
            $ta = $num_sn[7] > 3 ? $num_sn[0] : $num_sn[1];
            // print_r($num_sn);exit;
            //使用me的编号进行预测
            if (!empty($historyInfo['me_name']) && empty($historyInfo['ta_name'])) {
                $tmp = $ta;
                $ta = $me;
                $me = $tmp;
            }
            $day = date('Y-m-d');
            if (!empty($historyInfo['result_day'])) {
                $day = $historyInfo['result_day'];
            }

            if ($historyInfo['is_show_time_res'] != 1 && $historyInfo['contact'] != 1) { //没有建立联系
                $day = date('Y-m-d', strtotime($day) + 30 * 86400); //下月日期预测
            }

            //判断编码是否与日期和极端数字匹配
            $cd = substr($num_sn, 0, 2);
            $anq = [11, 12, 21, 22, 33, 44, 45, 54, 55, 66, 77, 78, 87, 88];
            //存在进下一步匹配
            if ($historyInfo['date1'] != '') {
                $times = $historyInfo['date1'];
                $timeslist = explode('-', $times);
                if (in_array($cd, $timeslist)) {
                    if ($historyInfo['contact'] == 0) {
                        if (in_array($cd, $anq)) {
                            $day = date('Y-m-d', strtotime($day)); //下月日期预测
                        }
                        //   else{
                        //     //$day = date('Y-m-d', strtotime($day) + 30 * 86400); //下月日期预测
                        //     throw new Exception("暂无结果!", 1);
                        //  }
                    }
                    // else{
                    //      $day = date('Y-m-d', strtotime($day) + 30 * 86400); //下月日期预测
                    // }
                }
            }
            //年月日咨询日期
            $date1 = $historyInfo['date1'];
            $lenDate1 = strlen($date1);
            if ($lenDate1 == 10) {
                $day = $date1;
            } elseif ($lenDate1 == 7) {
                $day = $date1.'-01';
            } elseif ($lenDate1 == 4) {
                $day = $date1.'-01-01';
            }
            // print_r($ta,$day);exit;
            $yuce = $this->_yuce($ta, $day);
            // print_r($yuce);exit;
            $yearGood = [];
            $monthGood = [];
            $dayGood = [];
            foreach ($yuce['years'] as $key => $value) {
                if ($value[2]) {
                    $yearGood[] = $value[0];
                }
                if (count($yearGood) >= 4) {
                    break;
                }
            }
            foreach ($yuce['months'] as $key => $value) {
                if ($value[2]) {
                    $monthGood[] = $value[0];
                }
            }
            foreach ($yuce['days'] as $key => $value) {
                if ($value[2]) {
                    $dayGood[] = $value[0];
                }
            }
            $easyNum = array_sum($yuce['ymd']);
            if ($historyInfo['is_show_time_res'] == 1) { //已知事件结果发生日期
                if ($lenDate1 == 10) {//年月日
                    $easy = $yuce['ymd'][2];
                } elseif ($lenDate1 == 7) {//年月
                    $easy = $yuce['ymd'][1];
                } elseif ($lenDate1 == 4) {//年
                    $easy = $yuce['ymd'][0];
                } else {
                    $easy = $easyNum > 1 ? 1 : 0;
                }
            } else { //无具体出结果日期事件
                $easy = $easyNum > 1 ? 1 : 0;
            }

            //startdate--enddate 时间区间预测
            $startdate = '';
            $enddate = '';
            $input_data_arr = json_decode($historyInfo['input_data'], true);
            if (is_array($input_data_arr)) {
                foreach ($input_data_arr as $value) {
                    if ($value[0] == 'startdate') {
                        $startdate = $value[1];
                    }
                    if ($value[0] == 'enddate') {
                        $enddate = $value[1];
                    }
                }
            }
            $startenddate = [];
            if ($startdate != '') {
                $tm = strtotime($startdate);
                $yuce2 = $this->_yuce($ta, $startdate);
                foreach ($yuce2['days'] as $key => $value) {
                    $nowDay = date('Y-m-d', $tm + $key * 86400);
                    if ($nowDay > $enddate || count($startenddate) >= 30) {
                        break;
                    }
                    if ($value[2]) {
                        $startenddate[] = $nowDay;
                    }
                }
            }

            //手机号中间4位用****替代
            $historyInfo['user_phone'] = substr_replace($historyInfo['user_phone'], '****', 3, 4);
            //我方 另一方名称处理
            if (!empty($historyInfo['me_name']) && empty($historyInfo['ta_name'])) {
                $historyInfo['ta_name'] = $historyInfo['user_phone'];
            } elseif (empty($historyInfo['me_name'])) {
                $historyInfo['me_name'] = $historyInfo['user_phone'];
            }
            $resp = [];
            if ($table == 'docs_latest') {
                $resp = [
                    'num_sn' => $infoMe['num_sn'],
                    'question_msg' => $historyInfo['person_fix_msg'],
                    'is_get_profit' => $infoMe['is_get_profit'], //我方做该事件是否可以获得利益
                    'me_wants' => $infoMe['zixun_wants'], //我方推进意愿 zixun_wants
                    'ta_idea' => $infoTa['ke_zhu_idea'], //另一方对我的想法 ta ke_zhu_idea
                    'ta_xinli' => $infoTa['zixun_xinli'], //另一方对于该事件此时的心理活动 ta zixun_xinli
                    'ta_wants' => $infoTa['zixun_wants'], //对方增加事件内容一 ta zixun_wants
                    //年：月：日：
                    'year_good' => implode('、', $yearGood),
                    'month_good' => implode('、', $monthGood),
                    'day_good' => implode('、', $dayGood),
                    'easy' => $easy,
                    'date1' => $historyInfo['date1'], //咨询日期
                    'startenddate' => implode("\n", $startenddate), //时间区间预测
                    'me_wants_date' => '我方有推进意愿的时间（年月日）'.$historyInfo['result_day'],
                    //对方增加事件内容二  我方有推进意愿的时间（年月日）
                    'ta_xintai' => $infoTa['zixun_xintai'], //客方心态 ta zixun_xintai
                    'me_xintai' => $infoMe['zixun_xintai'], //我方的心态 zixun_xintai
                    'things_degree' => $infoMe['things_degree'], //该事件总体推进难易度 things_degree
                    'me_xinli' => $infoMe['zixun_xinli'], //我方对于该事件此时的心理活动 zixun_xinli
                    'rate' => $historyInfo['rate'], //指定风险管理推送频率
                    'solution' => $infoMe['solution'], //解决方案
                    'is_show_time_res' => $historyInfo['is_show_time_res'],
                    'me_name' => empty($historyInfo['me_name']) ? '我方' : $historyInfo['me_name'],
                    'ta_name' => empty($historyInfo['ta_name']) ? '另一方' : $historyInfo['ta_name'],
                ];
                if ($historyInfo['date1'] != '') {
                    $resp['me_wants_date'] = '我方有推进意愿的时间（年月日）'.$historyInfo['date1'];
                }
            }
            if ($table == 'docs_works') {
                $resp = [
                    'num_sn' => $infoMe['num_sn'],
                    'question_msg' => $historyInfo['person_fix_msg'],
                    'is_get_profit' => $infoMe['me_is_getprofit'], //我方做该事件是否可以获得利益
                    'me_wants' => $infoMe['me_work_idea'], //我方推进意愿 zixun_wants
                    'ta_idea' => '', //另一方对我的想法 ta ke_zhu_idea
                    'ta_xinli' => $infoTa['me_xinli'], //另一方对于该事件此时的心理活动 ta zixun_xinli
                    'ta_wants' => $infoTa['me_work_idea'], //对方增加事件内容一 ta zixun_wants
                    //年：月：日：
                    'year_good' => implode('、', $yearGood),
                    'month_good' => implode('、', $monthGood),
                    'day_good' => implode('、', $dayGood),
                    'easy' => $easy,
                    'date1' => $historyInfo['date1'],
                    'startenddate' => implode("\n", $startenddate), //时间区间预测
                    'me_wants_date' => '我方有推进意愿的时间（年月日）'.$historyInfo['result_day'], //对方增加事件内容二  我方有推进意愿的时间（年月日）
                    'ta_xintai' => $infoTa['me_xintai'], //客方心态 ta zixun_xintai
                    'me_xintai' => $infoMe['me_xintai'], //我方的心态 zixun_xintai
                    'things_degree' => $infoMe['me_work_things_degree'], //该事件总体推进难易度 things_degree
                    'me_xinli' => $infoMe['me_xinli'], //我方对于该事件此时的心理活动 zixun_xinli
                    'rate' => $historyInfo['rate'], //指定风险管理推送频率
                    'solution' => $infoMe['cm_hope_me'], //解决方案
                    'is_show_time_res' => $historyInfo['is_show_time_res'],
                    'me_name' => empty($historyInfo['me_name']) ? '我方' : $historyInfo['me_name'],
                    'ta_name' => empty($historyInfo['ta_name']) ? '另一方' : $historyInfo['ta_name'],
                ];
                if ($historyInfo['date1'] != '') {
                    $resp['me_wants_date'] = '我方有推进意愿的时间（年月日）'.$historyInfo['date1'];
                }
            }
            if ($table == 'docs_emotion') {
                $resp = [
                    'num_sn' => $infoMe['num_sn'],
                    'question_msg' => $historyInfo['person_fix_msg'],
                    'is_get_profit' => '', //我方做该事件是否可以获得利益
                    'me_wants' => $infoMe['me_tuijin'], //我方推进意愿 zixun_wants
                    'ta_idea' => '', //另一方对我的想法 ta ke_zhu_idea
                    'ta_xinli' => $infoTa['me_xinli'], //另一方对于该事件此时的心理活动 ta zixun_xinli
                    'ta_wants' => $infoTa['me_tuijin'], //对方增加事件内容一 ta zixun_wants
                    //年：月：日：
                    'year_good' => implode('、', $yearGood),
                    'month_good' => implode('、', $monthGood),
                    'day_good' => implode('、', $dayGood),
                    'easy' => $easy,
                    'date1' => $historyInfo['date1'],
                    'startenddate' => implode("\n", $startenddate), //时间区间预测
                    'me_wants_date' => '我方有推进意愿的时间（年月日）'.$historyInfo['result_day'], //对方增加事件内容二  我方有推进意愿的时间（年月日）
                    'ta_xintai' => $infoTa['me_xintai'], //客方心态 ta zixun_xintai
                    'me_xintai' => $infoMe['me_xintai'], //我方的心态 zixun_xintai
                    'things_degree' => $infoMe['me_tuijin_degree'], //该事件总体推进难易度 things_degree
                    'me_xinli' => $infoMe['me_xinli'], //我方对于该事件此时的心理活动 zixun_xinli
                    'rate' => $historyInfo['rate'], //指定风险管理推送频率
                    'solution' => $infoMe['ta_hope_me'], //解决方案
                    'is_show_time_res' => $historyInfo['is_show_time_res'],
                    'me_name' => empty($historyInfo['me_name']) ? '我方' : $historyInfo['me_name'],
                    'ta_name' => empty($historyInfo['ta_name']) ? '另一方' : $historyInfo['ta_name'],
                ];
                if ($historyInfo['date1'] != '') {
                    $resp['me_wants_date'] = '我方有推进意愿的时间（年月日）'.$historyInfo['date1'];
                }
            }

            foreach ($resp as $kItem => $kVal) {
                // $resp['ta_name'] = substr_replace($resp['ta_name'], '****', 3, 4);
                $resp[$kItem] = str_replace('\n', "\n", $resp[$kItem]);
            }

            $result_title = Db::name('result_title')->field('*')->find();
            // if($resp['ta_name']!=''){
            //       $ta_names = substr_replace($resp['ta_name'], '****', 3, 4);
            // }else{
            //       $ta_names = '';
            // }

            foreach ($result_title as $kItem => $kVal) {
                $kVal = str_replace('{{me}}', $resp['me_name'], $kVal);
                $result_title[$kItem] = str_replace('{{ta}}', $resp['ta_name'], $kVal);
            }
            $resp['result_title'] = $result_title;

            $res['code'] = 0;
            $res['data'] = $resp;

            return json($res);
        } catch (\Throwable $th) {
            $res['code'] = 1;
            $res['msg'] = $th->getMessage();

            return json($res);
        }
    }

    private function _isGood($ids, array $goodIds)
    {
        if (is_array($ids)) {
            foreach ($ids as $id) {
                if (in_array($id, $goodIds)) {
                    return true;
                }
            }

            return false;
        }

        return in_array($ids, $goodIds);
    }

    private function _yuce($me, $date = '')
    {
        $tm = strtotime($date);
        $y = (int) date('Y', $tm);
        $m = (int) date('m', $tm);
        $d = (int) date('d', $tm);

        $year20 = [
            // [1944, 1963, [7, 8], 1, 0], //1944年--1963年=7和8都是
            [1964, 1983, 1, 0, 0], //1964年--1983年=1
            [1984, 2003, 2, 0, 0], //1984年--2003年=2
            [2004, 2023, 7, 0, 0], //2004年--2023年=7
            [2024, 2043, 3, 0, 0], //2024年--2043年=3
            [2044, 2063, 6, 0, 0], //2044年--2063年=6
            [2064, 2083, 8, 0, 0], //2064年--2083年=8
            [2084, 2103, 4, 0, 0], //2104年--2123年=4
            [2104, 2123, 5, 0, 0], //2104年--2123年=5
            [2124, 2143, [7, 8], 0, 0], //2124-2143=7和8都是
        ];
        //时间算法逻辑编号顺序：6～7～7a～4～5～5a～3～8～8a～2～1～1a
        $tag = ['6', '7', '7a', '4', '5', '5a', '3', '8', '8a', '2', '1', '1a'];

        $p = new paipan();
        $gz = $p->GetGZ($y, $m, $d, 0);
        $tmpYear = $gz[2]['ty'];
        $ydz = $gz[1][0];
        $mdz = $gz[1][1];
        $ddz = $gz[1][2];

        $years = [];
        $months = [];
        $days = [];
        //预测12年
        // for ($i = 0; $i < 12; $i++) {
        //     $years[] = [$tmpYear + $i, $tag[($ydz + $i) % 12], 0];
        // }
        for ($i = 0; $i < 12; ++$i) {
            $idx = (($y - 2020) % 12 + $i) % 12;
            $years[] = [$y + $i, $tag[$idx], 0];
        }
        //预测12月数据
        // for ($i = 0; $i < 12; $i++) {//干支历月份
        //     $months[] = [($m - 1 + $i) % 12 + 1, $tag[($mdz + $i) % 12], 0];
        // }
        for ($i = 0; $i < 12; ++$i) { //阳历月份
            $tmpMonth = ($m - 1 + $i) % 12 + 1;
            $months[] = [$tmpMonth, $tag[$tmpMonth % 12], 0];
        }
        //预测30天数据
        for ($i = 0; $i < 30; ++$i) {
            $days[] = [(int) date('d', $tm + $i * 86400), $tag[($ddz + $i) % 12], 0];
        }

        $tm = time();
        $y = date('Y', $tm);
        $m = date('m', $tm);
        $d = date('d', $tm);
        $p = new paipan();
        $gz = $p->GetGZ($y, $m, $d, 0);

        $tag = ['6', '7', '7a', '4', '5', '5a', '3', '8', '8a', '2', '1', '1a'];
        $tmpYear = $gz[2]['ty'];
        $ydz = $gz[1][0];
        $mdz = $gz[1][1];
        $ddz = $gz[1][2];
        $data = [];
        for ($i = 0; $i < 12; ++$i) {
            $data['years'][] = [$tmpYear + $i, $tag[($ydz + $i) % 12], 0];
        }
        for ($i = 0; $i < 12; ++$i) {
            $data['months'][] = [($m - 1 + $i) % 12 + 1, $tag[($mdz + $i) % 12], 0];
        }
        for ($i = 0; $i < 30; ++$i) {
            $data['days'][] = [(int) date('d', $tm + $i * 86400), $tag[($ddz + $i) % 12], 0];
        }

        $year20Good = [];
        $yearGood = [];
        $monthsGood = [];
        $daysGood = [];
        if (in_array($me, [1, 2])) {
            $year20Good = [1, 2, 6, 7, 8];
            $timeGood = ['1', '2', '8', '7', '1a', '8a', '7a'];
            $yearGood = $timeGood;
            $monthsGood = $timeGood;
            $daysGood = $timeGood;
        }
        if (in_array($me, [3])) {
            $year20Good = [3, 4, 5, 7, 8];
            $timeGood = ['4', '5', '3', '5a'];
            $yearGood = $timeGood;
            $monthsGood = $timeGood;
            $daysGood = $timeGood;
        }
        if (in_array($me, [4, 5])) {
            $year20Good = [3, 4, 5, 6];
            $timeGood = ['6', '4', '5', '5a'];
            $yearGood = $timeGood;
            $monthsGood = $timeGood;
            $daysGood = $timeGood;
        }
        if (in_array($me, [6])) {
            $year20Good = [1, 2, 4, 5, 6];
            $timeGood = ['1', '2', '6', '1a'];
            $yearGood = $timeGood;
            $monthsGood = $timeGood;
            $daysGood = $timeGood;
        }
        if (in_array($me, [7, 8])) {
            $year20Good = [1, 2, 3, 7, 8];
            $timeGood = ['7', '8', '3', '7a', '8a'];
            $yearGood = $timeGood;
            $monthsGood = $timeGood;
            $daysGood = $timeGood;
        }

        $year20GoodBad = 0;
        $yearGoodBad = 0;
        $monthGoodBad = 0;
        $dayGoodBad = 0;
        foreach ($year20 as $key => $value) {
            $year20[$key][4] = $this->_isGood($year20[$key][2], $year20Good) ? 1 : 0;
            //当前所属20年的 good bad
            if ($tmpYear >= $year20[$key][0] && $tmpYear <= $year20[$key][1]) {
                $year20GoodBad = $year20[$key][4];
            }
        }
        foreach ($years as $key => $value) {
            $years[$key][2] = $this->_isGood($years[$key][1], $yearGood) ? 1 : 0;
        }
        foreach ($months as $key => $value) {
            $months[$key][2] = $this->_isGood($months[$key][1], $monthsGood) ? 1 : 0;
        }
        foreach ($days as $key => $value) {
            $days[$key][2] = $this->_isGood($days[$key][1], $daysGood) ? 1 : 0;
        }
        $yearGoodBad = $years[0][2]; //当前年的 good bad
        $monthGoodBad = $months[0][2]; //当前月的 good bad
        $dayGoodBad = $days[0][2]; //当前日的 good bad

        return [
            'date' => $date,
            'years20' => $year20,
            'years' => $years,
            'months' => $months,
            'days' => $days,
            'year20' => $year20GoodBad,
            'ymd' => [$yearGoodBad, $monthGoodBad, $dayGoodBad],
        ];
    }

    /**
     * 获取当前用户 是否可以使用 咨询.
     */
    public function getUserIsUse()
    {
        $res = ['code' => 1, 'data' => [], 'msg' => ''];
        try {
            $cid3Map = config('app.cid3_map');
            $cid3 = input('type', ''); //获取套餐所属分类
            //是否是ios  1 是 0 否
            $isIos = input('isIos', 0);
            $user_phone = input('user_phone', '');
            if (empty($user_phone)) {
                throw new Exception('用户唯一凭证为必传标识', 1);
            }
            if (empty($cid3Map[$cid3])) {
                throw new Exception('获取会员套餐类型失败', 1);
            }
            $userInfo = Db::name('member')->field('*')->where(['phone' => $user_phone])->find();
            if (empty($userInfo)) {
                throw new Exception('获取会员信息', 1);
            }
            $vip = $cid3Map[$cid3];
            $combo_type = $vip['once'];
            $combo_type2 = $vip['month'];
            $vipKey = $vip['once_field'];
            $monthvipKey = $vip['month_field'];
            // 默认获取的是次卡套餐费用
            $comboInfo = Db::name('combos')->field('*')->where(['combo_type' => (int) $combo_type])->find();
            // 页面需要展示, 月卡套餐费用. combo表,填充数据的时候, 注意: 一个类型对应两行数据. 单数--次卡,双数--月卡
            $comboMonthInfo = Db::name('combos')->field('*')->where(['combo_type' => bcadd($combo_type, 1)])->find();

            if (empty($comboInfo) || empty($comboMonthInfo)) {
                throw new Exception('获取会员套餐信息失败', 1);
            }
            $freeTimes = Db::name('config')->where('id', 21)->value('value');
            $res['data']['zifei'] = $comboInfo['fee']; // 获取单次付费标准
            $res['data']['month_zifei'] = $comboMonthInfo['fee']; // 获取月卡付费标准
            $res['data']['times'] = $freeTimes ?? 1; //每天免费次数
            $res['data']['is_used'] = ($userInfo[$vipKey] > 0 || $userInfo[$monthvipKey] > 0) ? 1 : 0; //有次卡数 或 包月未过期
            $res['data']['combo_type'] = $combo_type; //次卡套餐类型
            $res['data']['combo_type2'] = $combo_type2; //月卡套餐类型
            $res['data']['audit'] = $this->audit && $isIos ? 1 : 0; //审核中且是ios  页面不会显示付费
            $res['data']['uid'] = $userInfo['id'];
            // 中医诊断是否有 体验次数. type=1-1-5&cid3=19
            $res['data']['is_medical_type'] = ($cid3 == 19) ? 1 : 0;
            $res['data']['medical_once_nums'] = $userInfo['medical_once_nums'];

            $res['code'] = 0;

            return json($res);
        } catch (\Throwable $th) {
            //throw $th;
            $res['code'] = 1;
            $res['msg'] = $th->getMessage();

            return json($res);
        }
    }

    /**
     * 企业证书和案例集.
     */
    public function certificateList()
    {
        $res['data'] = [
                ['img' => 'https://aiw.oss-cn-beijing.aliyuncs.com/zs/p1.jpg', 'title' => '2023金熊猫全球创新创业大赛入围'],
                ['img' => 'https://aiw.oss-cn-beijing.aliyuncs.com/zs/eg1.jpg', 'title' => '会否收到回复'],
                ['img' => 'https://aiw.oss-cn-beijing.aliyuncs.com/zs/p2.jpg', 'title' => '第三届BPAA创业组TOP50'],
                // ['img'=> "https://aiw.oss-cn-beijing.aliyuncs.com/zs/eg2.png",'title'=>'奇玑策超算'],
                ['img' => 'https://aiw.oss-cn-beijing.aliyuncs.com/zs/eg3.png', 'title' => '奇玑策金融科技'],
                ['img' => 'https://aiw.oss-cn-beijing.aliyuncs.com/zs/p3.jpg', 'title' => '华为技术认证及授权'],
                ['img' => 'https://aiw.oss-cn-beijing.aliyuncs.com/zs/eg7.jpg', 'title' => '摇号入学'],
                ['img' => 'https://aiw.oss-cn-beijing.aliyuncs.com/zs/p4.jpg', 'title' => '软件产品证书'],
                ['img' => 'https://aiw.oss-cn-beijing.aliyuncs.com/zs/eg4.png', 'title' => '奇玑策政策预测'],
                ['img' => 'https://aiw.oss-cn-beijing.aliyuncs.com/zs/p5.jpg', 'title' => '软件和信息服务业协会专家'],
                ['img' => 'https://aiw.oss-cn-beijing.aliyuncs.com/zs/eg5.jpg', 'title' => '热卷价格'],
                ['img' => 'https://aiw.oss-cn-beijing.aliyuncs.com/zs/p6.jpg', 'title' => '软件著作权'],
                ['img' => 'https://aiw.oss-cn-beijing.aliyuncs.com/zs/eg6.jpg', 'title' => '考博'],
                ['img' => 'https://aiw.oss-cn-beijing.aliyuncs.com/zs/p7.jpg', 'title' => '专利1'],
                ['img' => 'https://aiw.oss-cn-beijing.aliyuncs.com/zs/eg7.jpg', 'title' => '摇号入学'],
                ['img' => 'https://aiw.oss-cn-beijing.aliyuncs.com/zs/p8.jpg', 'title' => '专利2'],
                ['img' => 'https://aiw.oss-cn-beijing.aliyuncs.com/zs/eg8.jpg', 'title' => '股票'],
                ['img' => 'https://aiw.oss-cn-beijing.aliyuncs.com/zs/p9_1.jpg', 'title' => '网络安全志愿服务站'],
            ];
        $res['code'] = 0;

        return json($res);
    }

    /**
     * 调整监测预警推送频率.
     */
    public function setRate()
    {
        $res = ['code' => 1, 'data' => [], 'msg' => ''];
        try {
            //code...$res['code'] = 0;
            $rate = (int) input('rate', '0');
            // 个人 咨询,历史记录
            $historyId = (int) input('history_id', '0');
            if (empty($historyId)) {
                throw new Exception('咨询记录ID不能为空!', 1);
            }
            // 更新订单状态
            $updateData = [
                'rate' => $rate,
            ];
            $updateRes = Db::name('new_user_question_history')->where(['id' => $historyId])->update($updateData);
            if (!$updateRes) {
                throw new Exception('更新设置失败', 1);
            }
            $res['code'] = 0;

            return json($res);
        } catch (\Throwable $th) {
            //throw $th;
            $res['code'] = 1;
            $res['msg'] = $th->getMessage();

            return json($res);
        }
    }

    // /关键词搜索
    public function searchQuestion()
    {
        $res = ['code' => 1, 'data' => [], 'msg' => ''];
        $data = [];
        try {
            $keyword = input('keyword', '');
            $list = Db::name('question')->field('id,cid1,cid3,title')->where('title', 'like', '%'.$keyword.'%')->select();
            $res['code'] = 0;
            $res['data'] = $list;

            return json($res);
        } catch (\Throwable $th) {
            //throw $th;
            $res['code'] = 1;
            $res['msg'] = $th->getMessage();

            return json($res);
        }
    }

    //生成二维码
    public function generateQrcode()
    {
        //大分类
        $typeArr = [
            // '7'     =>  '1-1-1',
            // '8'     =>  '1-1-2',
            // '9'     =>  '1-1-3',
            // '10'    =>  '1-1-4',
            // '11'    =>  '2-1-1',
            // '12'    =>  '2-1-2',
            // '13'    =>  '2-1-3',
            // '14'    =>  '2-2-1',
            // '15'    =>  '2-2-2',
            // '16'    =>  '2-2-3',
            // '17'    =>  '2-2-4',
            // '18'    =>  '2-3-1',
            // '19'    =>  '1-1-5',
            // '20'    =>  '6-5-6',
            ];
        foreach ($typeArr as $k => $v) {
            $ids = Db::name('question')->where(['cid3' => $k])->field('id')->select();
            foreach ($ids as $id) {
                $img = './static/qrcode/'.$k.'-'.$id['id'].'.jpg';
                $wechatPayConf = config('app.wechat_pay');
                // 支付平台分配给开发者的应用ID
                $appid = $wechatPayConf['mini_appid'];
                // 商户API 密钥
                $secret = $wechatPayConf['mini_secret'];
                $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$secret;
                $oauth2 = json_decode(file_get_contents($url), true);
                //TODO
                //无限制获取小程序码，请求这个接口,scene获取不到暂时用下面的方法
                // $qcode ="https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=".$oauth2['access_token'];
                // $param = json_encode(array("page"=>"pages/result5/index","scene"=>"history_id=144650"));
                //获取二维码 只能获取10w个 暂时用到
                $qcode = 'https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token='.$oauth2['access_token'];

                $param = json_encode(['path' => 'pages/newDetail/indexV2?type='.$typeArr[$k].'&cid3='.$k.'&qid='.$id['id'], 'width' => 430]);
                // //POST参数
                $result = httpRequest($qcode, $param, 'POST');

                // //生成二维码
                    $res = file_put_contents($img, $result); //保存服务器用到的,qrcode.png这个就是你生成的二维码图片,可以存到你指定的路径,
            }
        }
    }

    //前台文字设置
    public function gettext()
    {
        //首页文字
        $text = '国家超算互联网联合体理事成员国家科技成果认定，华为技术互认授权，BSIA专家库人工智能组评委开发。无明智囊[AI智囊系统]为您提供如摇号入学、考学考研等预测并提供解决方案建议。过去无可挽回，未来可以改变。
                 团体-公关(选择评估、竞标、内控、股市等自动预测)、战略-行业、战略、项目、内控等；
                 个人-项目、事业(考学、面试)、情感、公关(摇号入学、股市等自动预测)、健康预测。';

        $text1 = '*对方经常拖延或者极端及短时间不可能请选[否]，有明确办结时限或其他选[是]';
        $text7 = '*考学等结果时间明确选[是]，极端或短时间不可能请选[否],*高考考研小升初录取通知（书）时间选[年]'; //针对考学
        $text2 = '咨询事情的时间单位';

        //团体用户文字
        $text3 = ' 本产品被全球算法最佳实践典范大赛收录。工信部国家超算互联网联合体理事成员，工信部人工智能标准化技术委员会工作组成员，互联网医疗健康产业联盟“算力产业发展方阵”算力+医疗健康工作组成员单位，网信算备110111655486701240015号';
        //个人用户文字
        $text4 = ' 本产品被全球算法最佳实践典范大赛收录。工信部国家超算互联网联合体理事成员，工信部人工智能标准化技术委员会工作组成员，互联网医疗健康产业联盟“算力产业发展方阵”算力+医疗健康工作组成员单位，网信算备110111655486701240015号';
        //团体用户--下公关维护和战略部署文字
        $text5 = ' 本产品被全球算法最佳实践典范大赛收录。工信部国家超算互联网联合体理事成员，工信部人工智能标准化技术委员会工作组成员，互联网医疗健康产业联盟“算力产业发展方阵”算力+医疗健康工作组成员单位，网信算备110111655486701240015号';
        $text6 = '关键词,例如:健康、高考、股市、摇号入学等';

        $res['code'] = 0;

        $res['data'] = $text; //首页文案废弃替换成轮播
        $res['data1'] = $text1;
        $res['data2'] = $text2;
        $res['data3'] = $text3;
        $res['data4'] = $text4;
        $res['data5'] = $text5;
        $res['data6'] = $text6;
        $res['data7'] = $text7;
        //轮播
        $res['banner'] =
            [
                // 'https://aiw.oss-cn-beijing.aliyuncs.com/zs/b1.jpg',
                'https://aiw.oss-cn-beijing.aliyuncs.com/zs/b2.jpg',
                'https://aiw.oss-cn-beijing.aliyuncs.com/zs/b3.png',
                'https://aiw.oss-cn-beijing.aliyuncs.com/zs/b4.jpg',
                'https://aiw.oss-cn-beijing.aliyuncs.com/zs/b5.png',
                'https://aiw.oss-cn-beijing.aliyuncs.com/zs/p9_1.jpg',
                // 'https://aiw.oss-cn-beijing.aliyuncs.com/zs/zyy.jpg',
                'https://aiw.oss-cn-beijing.aliyuncs.com/zs/yiyao.jpg',
                'https://aiw.oss-cn-beijing.aliyuncs.com/zs/honer.jpg',
                'https://aiw.oss-cn-beijing.aliyuncs.com/zs/new_zs1.png',
                'https://aiw.oss-cn-beijing.aliyuncs.com/zs/new_zs2.jpg',
                'https://aiw.oss-cn-beijing.aliyuncs.com/zs/new_zs_3.jpg',
                'https://aiw.oss-cn-beijing.aliyuncs.com/zs/new_zs_4.jpg',
                'https://aiw.oss-cn-beijing.aliyuncs.com/zs/new_zs_5.jpg',
            ];

        return json($res);
    }

    public function service()
    {
        $res['code'] = 0;
        $res['data']['text'] = '有疑问找专家,一对一服务,资深咨询师300元,专家咨询师800元';
        $res['data']['img'] =
            [
                // ['name'=>'高级咨询师--琳达','img'=>'https://docs.spacetimesc.com/static/qrcode/20-66.jpg'],
                // ['name'=>'高级咨询师','img'=>'https://docs.spacetimesc.com/static/qrcode/20-66.jpg'],
                ['name' => '专家咨询师-王诩', 'img' => 'https://docs.spacetimesc.com/static//imgs/wangxu.jpg'],
            ];

        return json($res);
    }

    
}
